简体   繁体   中英

How to control double precision computing to avoid rounding errors in C++ linux x86_64?

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

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!

PS 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.

PPS Go look at GMP . It might be your best hope.

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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM