1

In a C++ code on linux x86_64, I need to double precision computing (+ or -).

26.100000000000001 - 26 + 0.10000000000000001

I got:

0.20000000000000143

I want to get 0.2.

here, the display format is not import, the computing results will be used for some if-else branch conditions. So, I only want the if-else conditions compare the 4 digits after the decimal digit.

It seems a rounding error ?

How to restrict the computing precision to 4 digits after decimal point ?

I do not want to call any functions in order to avoid overhead.

I do not want to use stringstream due to transformation overhead.

Any better ideas ?

thanks

3 Answers 3

8

The computing precision is fine. It's the display precision you're trying to control. You can do that with setprecision() if using <iostream> or a formatter like "%.4f" if using <stdio.h>.

You are already calling functions since you are displaying the result as decimal!

P.S. 0.1 cannot be exactly represented by a float, double, or any binary-mantissa format. It factors into (1/2) * (1/5), and decimal 1/5 is an infinitely-repeating digit sequence in binary.

P.P.S. Go look at GMP. It might be your best hope.

Sign up to request clarification or add additional context in comments.

3 Comments

here, the display format is not import, the computing results will be used for some if-else branch conditions. So, I only want the if-else conditions compare the 4 digits after the decimal digit.
@user1002288 What you're trying to do is not possible with binary floating-point. No amount of rounding hacks will make decimal arithmetic on binary floating-point work like magic..
@user1002288 You can just add some magic epsilon value to all you floating-precision comparisons. Like if (a==b) {} transforms into if (abs(a-b) < 1e-4) {}. This is the best thing you can do using floating-point arithmetics.
2

If you just want to print it it, you can use printf("%10.4lf"). You can alter the precision to anything you want, of course.

2 Comments

here, the display format is not import, the computing results will be used for some if-else branch conditions. So, I only want the if-else conditions compare the 4 digits after the decimal digit.
oh you mean display format is not importANT! ok.. you can try multiplying with 10^(precision) [precision=4 in your case].
1

If you are only interested in equality up to four decimal places, multiply everything by 10,000 and use integer arithmetic. (You might need to round after multiplying by 10,000.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.