0

I'm trying to have this function work, but i'm not getting the results expected. I fully believe it because I'm new to Python.... Here is my code:

waterLevel = (-(25/144) * sensorValue) + (14725/72) ;

And here is the equation:

y=-25x/144 + 14725/72

So when x=1178 then y=0 (y=waterLevel) and when x=602 then y=100.

I am getting this, when x=1178 then y=204.

What am I doing wrong here?

Update This is a different question because I didn't know it was floating point python nonsense .... just that my math wasn't working. Just because the answer is the same doesn't mean it is a duplicate. ;)

schumacherj
  • 1,284
  • 5
  • 18
  • 33

2 Answers2

4

You are falling foul of integer division as opposed to float division.

In Python 2.x 25/144 will produce integer division which means it will result in 0.

If you're going to be dealing with floating point numbers then you should use floating point numbers, i.e. 25.0/144.0.

In Python 3.x the division of integers will default to returning the floating point value and instead you must explicitly choose integer division using //. If you would like this behaviour in Python 2 then use from __future__ import division at the top of your script (thanks to jwodder for the comment).

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
0

Use floats instead of ints

waterLevel = (-(25.0/144.0) * sensorValue) + (14725.0/72.0)

By the way, there is an adicional parethesis in the beginning of the equation, is it a typo?

Magnun Leno
  • 2,728
  • 20
  • 29
  • @Magnum I was hoping to be more clear in my intentions so that when others view my code they know exactly what I mean. – schumacherj Jun 11 '14 at 21:31