1

I love javascript, don't get me wrong, but my problem is I currently want to develop open source web applications for scientific computations and javascript's arithmetic isn't exactly the most precise. I've scripted server-side, but I prefer client-side for the obvious reasons that the experience for the user is generally smoother and there is less load on the server.

What are my options as far as working around this issue? I've read somewhere that you can implement languages on top of javascript--would this be worth it and what does this look like? If I do, say, implement python on top of javascript, does that mean the client needs a python interpreter to use the site?

I just can't handle

0.1 + 0.2 == 0.3 // is False
grasingerm
  • 1,955
  • 2
  • 19
  • 22
  • 1
    just for the record. http://stackoverflow.com/questions/588004/is-javascripts-math-broken – Tim Sep 12 '12 at 18:49
  • I think what you need is to switch the sandbox of the client. With pure javascript or some language that translates to javascript, you will have problems with the precision that browsers use. To use precise arithmetic operations, you may have to switch from pure javascript to Flash, Java, ActiveX or something else. – Gilberto Torrezan Sep 12 '12 at 18:50
  • 1
    Just FYI, you'll find the exact same issue (i.e., `0.1+0.2!=0.3`) in C, C++, Java, Python, and any other language that uses floating point numbers. Sometimes, you can opt to use native [fixed point numbers](https://en.wikipedia.org/wiki/Fixed-point_arithmetic#Implementations) if you're lucky enough to have a language that supports them; otherwise, you'll have to use a number library. – apsillers Sep 12 '12 at 19:23

2 Answers2

4

Floating points operations are approximated calculations

This is not wrong see more about it

Weird programing behavior

THis is not specific to javascript but common in programming as a whole

Here is what i get on chrome:

0.1 + 0.2 = 0.30000000000000004;

And here is a simple but excellent read on the subject:

What Every Programmer Should Know About Floating-Point Arithmetic

Why don’t my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and instead I get a weird result like 0.30000000000000004?

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your “0.1” is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

Community
  • 1
  • 1
Ibu
  • 42,752
  • 13
  • 76
  • 103
2

There are a few libraries that allow for much better mathematical operations:

However, I would very strongly suggest doing this server side. You could easily do it via AJAX and not have to worry about responsiveness. Javascript just wasn't really built for numbers.

Phillip Schmidt
  • 8,805
  • 3
  • 43
  • 67