What is the best way to handle floating point errors?

So, I have a Javascript script that adds small fragments together in a loop and its possible that it will add 0.2 to 0.1. Then this value is passed to another function, but the problem is that I need 0.3 to feed exactly, and not 0.30000000000000004.

What is the easiest way to provide the correct and accurate number. Please note that his ability to get 0.25 + 0.125, etc. Adding to just rounding to 1 decimal will not solve the problem.

It is also possible to add 0.2 + 0.10000000000000004, although this is very, very unlikely!

+5
source share
1 answer

There is no easy way to avoid rounding errors in general-purpose floating-point arithmetic. The number 0.3 does not have an exact binary representation of a floating point.

I would suggest reading What every computer scientist needs to know about floating point arithmetic in order to get acquainted with the tradeoffs inherent in floating point representation of numbers.

To solve your problem, you should ask yourself a few questions:

  • How strict is your accuracy requirement? Why is 0.30000000000000004 outside the field for error? Is rounding the results acceptable?
  • Is there a way to represent your numbers and do most of your arithmetic with integers? For instance. if you know that you meet only rational numbers, they can be represented using an integer quotient and an integer denominator. From there, you can try to postpone casting to swim for as long as possible to prevent cumulative rounding errors.
  • If you cannot perform integer calculations, is there an alternative data type like BigDecimal ?

Ultimately, when it comes to issues with floating point precision, you often have to adapt the solution to the requirements of your particular problem.

+1
source

All Articles