0

SOLVED:

Read:

  1. Is floating point math broken?
  2. How to deal with floating point number precision in JavaScript?

Just get any JavaScript processing environment and type:

150.3 + 150.03

Simple calculation, but it doesn't seem to give the right result (it doesn't matter if you write "150.30 + 150.03" or so).

It gives the result: 300.33000000000004.

Any ideas why?

PS: I read some articles both on Stack Overflow and Wikipedia about some wrong computing calculations due to finite precision, but nothing seemed relevant to my case.

Community
  • 1
  • 1
Daniel Iancu
  • 435
  • 1
  • 5
  • 12
  • 1
    It's relevant. The answer is to truncate your data to the appropriate precision. –  Apr 15 '14 at 07:04
  • "_I read some articles...wrong computing calculations...nothing seemed relevant_". **Read them again**, it's exactly your case. For exercise try to write floating point representation of "0.03" and you'll see where it comes from. – Adriano Repetti Apr 15 '14 at 07:04
  • An acceptable error. Check out [Elegant workaround for JavaScript floating point number problem](http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem) – loxxy Apr 15 '14 at 07:05
  • @loxxy Thank you very much. We can call this a duplicate. – Daniel Iancu Apr 15 '14 at 07:12
  • @axiom Nope. It's not actually a duplicate. It's the solution. Hence I edited my automated comment. – loxxy Apr 15 '14 at 07:13
  • @Adriano The articles I read where focused on pi and other mathematical constants (like e). – Daniel Iancu Apr 15 '14 at 07:16
  • So that's why Linux Torvalds said Java is a horrible language ("JavaScript uses 64-bit floating point representation, which is the same as Java's double."). – Daniel Iancu Apr 15 '14 at 07:21
  • You don't need to find an example for every possible number. What applies to a number will apply to all the others. Anyway your first link addresses **exactly** your problem. Moreover...do you think in C there is something different? It's how floating point numbers are represented, no matters if Java, JavaScript, C#, Perl or C++ (and 64 is DOUBLE precision). Well they're somehow different in implementation (most evident example AFAIK is Fortran) but it's a _limit_ of binary representation for floating points (so 0.3 won't be exact for single/double types in all that languages). – Adriano Repetti Apr 15 '14 at 08:23

0 Answers0