-1

Why does javascript math operations produce different results than python? and how to fix it?

python:

>> 4-((4/3)*3)+1
>> 2

javascript:

>> 4-((4/3)*3)+1
>> 1

2 Answers2

3

In python, 4/3 == 1, since it is an an integer operation. In JS it is a floating point operation, and therefore 4/3 === 1.3333333333333333.

If you want floating point operations in python, have floating point in the equation. E.g.

4-((4/3)*3)+1 == 2 (Integer)

4-((4.0/3.0)*3)+1 == 1 (Float)

MoeSattler
  • 6,684
  • 6
  • 24
  • 44
  • It's even better to do `from __future__ import division` to force Python 2 to do float division. – PM 2Ring Dec 08 '16 at 13:18
  • Tip for especially lazy readers like myself: you only need one argument to be a float to get floating point division, and a float literal can end with a decimal point, so you can accomplish this by just adding a single dot: `4-((4./3)*3)+1` – Kevin Dec 08 '16 at 13:27
1

Actually javascript produces decimal values of 1.333333 for 4/3 and it multiplied with 3 which tends to produce 4. 1 is the correct result for 4-((4/3)*3)+1 but if you want 2 as your result then you need to parse the value of 4/3 to int so 1.333333 will become 1 which is multiplied with 3 will produce 3.

 alert(4-(parseInt(4/3)*3)+1)
vijay
  • 926
  • 7
  • 15