0
tweeninc=0.0
tranVal=0.0
increment=1
tweenVal=0.0
increment1=0.1
while True:



    if tweenVal==1.0:
        increment1=-0.1
    if tweenVal==0.0:
        increment1=0.1
    if tranVal==14:
        increment=-1
    if tranVal==-14:
        increment=1
    tranVal=tranVal+increment
    tweenVal=tweenVal+increment1

    print tweenVal

inside the while loop why does the tweenVal keep going beyond 1.

it goes .8,.9,1.0,1.1,1.2,1.3...1.9... and I want it to go .8,.9,1.0,.9,.8,.7...0,.1,.2

Im doing the same thing for the value under it which goes between -14 and 14 does it have something to do with it being a floating point?

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • I suggest you change one of your tags to a language tag. – takendarkk Apr 16 '14 at 22:02
  • thanks will people still see this question because it isn't "new" – user3469859 Apr 16 '14 at 23:49
  • It is still visible to all. Also, I do think your problem lies with the normal floating point problems. Try to introduce a variance variable (something like 0.0001) and if the tweenVal is within that variance of your target, then do your operation. – takendarkk Apr 16 '14 at 23:53
  • 1
    Voting to close as duplicate. There are lots of questions on Stack Overflow about why floating-point calculations give unexpected results. Here is one: [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Thomas Padron-McCarthy Apr 17 '14 at 15:27

1 Answers1

2

Floating point encoding is imprecise and can not represent all possible values. What you think of as 0.1 is actually 0.10000000149011612 when converted to double precision ieee754 format. Bottom line -- do not do exact comparisons on floating point values.

Something like this should work better:

if tweenVal > 0.95:
    increment1=-0.1
if tweenVal < 0.05:
    increment1=0.1
ArtemB
  • 3,496
  • 17
  • 18