Search code examples
cfloating-pointfloating-accuracy

C: How to perform accurate floating-point operations?


I am well aware that 0.1+0.2 != 0.3 because of precision errors. However I need it to be equal to 0.3.

My solution would be to :

  • Declare an add function that returns the correct double.
  • Inside this function, add the two numbers then round to the 13th digit.

This would work for 0.49999999999999994 and 0.30000000000000004.

How would I implement such a rounding function? Is there another way?


Solution

  • The problem existed from the moment the decimal fractions 0.1 and 0.2 were converted to double, getting 0.1000000000000000055511151231257827021181583404541015625 and 0.200000000000000011102230246251565404236316680908203125. Both are little bigger than the decimal fraction. The nearest double to their sum, 0.3000000000000000444089209850062616169452667236328125, is the next double up from 0.3. The nearest double to 0.3 is smaller, 0.299999999999999988897769753748434595763683319091796875

    If you need decimal arithmetic to be exact, not just very, very close, you need to use a decimal arithmetic type, not double.