Victor
Victor

Reputation: 3688

Setting double to a limitated value, exclusive

I have a double value in one of my classes, with has an upper bound.

The problem is when I try to set this variable to a value with is greater then its limit. When that happen I would like to set it to the closest value inside the limits.

And an awkward situation happens when I try .getLimit() - Double.MIN_VALUE

Which has no effect.

Can anyone clarify this for me? Thanks in advance.

Upvotes: 0

Views: 35

Answers (2)

markspace
markspace

Reputation: 11020

I think you want Math.ulp():

  double d = 1.234566789123456789e20;
  double delta = d - Math.ulp( d );
  System.out.println( d > delta );

Prints true.

Upvotes: 1

ajb
ajb

Reputation: 31689

If you can use Java 8, the Math.nextDown function appears to be exactly what you're looking for.

If you can't use Java 8, the relevant line from the source of Math.nextDown is:

return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
                                           ((d > 0.0d)?-1L:+1L));

You can simplify this a bit if you know d is positive.

Upvotes: 1

Related Questions