Problems with floating point and modulus

T

Tasperian Jigs

Hi,

I try to get a 'next value' (depending on 'nextNumber') for a double with
this method.

public static double nextNearest(double value, double nextNumber)
{
final double remainder = value % nextNumber;
return value - remainder + (remainder > 0 ? nextNumber : 0);
}

But the 'remainder' variable does not get the exact remainder after the
modulus. Is there another way to realise this method so the return result
is the exact double that i want? I'm aware of floating point inaccuracies,
that's why I ask this question ..

Thanks,

J
 
T

Tasperian Jigs

But the 'remainder' variable does not get the exact remainder after the

With the example values of 0.7 and 0.01. The outcome is in that case
0.7000000000000001
 
P

Patricia Shanahan

Tasperian said:
Hi,

I try to get a 'next value' (depending on 'nextNumber') for a double with
this method.

public static double nextNearest(double value, double nextNumber)
{
final double remainder = value % nextNumber;
return value - remainder + (remainder > 0 ? nextNumber : 0);
}

But the 'remainder' variable does not get the exact remainder after the
modulus. Is there another way to realise this method so the return result
is the exact double that i want? I'm aware of floating point inaccuracies,
that's why I ask this question ..

Thanks,

J

Can you explain a bit more of the context and requirements?

There are generally a couple of ways of dealing with rounding error when
you need to do tests:

1. Use a small fudge factor, traditionally called "epsilon". To apply
this, you need to find a value for epsilon that is smaller than any
non-zero number you would get if you were doing exact real arithmetic,
but larger than the rounding error.

Something around 1e-12 times the larger input value might work.

Your test would become remainder>epsilon rather than remainder>0.

2. Do the controlling stuff in some form of exact arithmetic, such as
scaled integer. If all interesting numbers are representable as decimal
fractions with a bounded number of digits, consider BigDecimal.

Patricia
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top