Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top