3
$\begingroup$

I'm trying to regulate an animation with a driver. However I got a problem with the equations. As reported in the picture I've a variable that is "0.9". I want to take the 9. My idea was to add a simple equation "int(var*10)". However I get "8" instead of "9".

enter image description here

If I directly add in the expression "int(.9*10)" instead I get "9".

Any suggestion? At the moment I'm not attaching the blender file since is quite heavy, however if you think that could be important I'll do that.

Thanks to everyone! T

[UPDATE]: I've noticed that the problems seems to be that the variable value, although seems ".9", actually is ".89999999". Since this I solved my problem using the following expression "int(var*10+.0001)". However I don't think that this should be the correct solution. I mean, if I add a ".9" value, I would expect to get exactly that, or maybe I'm misunderstanding something? Thanks to everyone.

enter image description here

$\endgroup$
1

1 Answer 1

4
$\begingroup$

Due to the nature of how the values are held in the computer, 'float' values are typically just an approximation (although to quite a high precision). The int(...) function literally takes just the interger portion of the value and so you are getting the unexpected value 8 instead of 9 when there is a minor rounding difference (and since 0.1 cannot be held exactly in Binary representations this can occur quite frequently).

The solution could be to simply use round instead of int since this will automatically round up or down to the nearest integer - instead of simply truncating off the fractional part.

ie, instead of :

int(var * 10)

Use :

round(var * 10)

EDIT : You can combine these two functions to give you a threshold of how accurate the input value needs to be for each result. For example :

int(round(var * 100) / 10)

This will first round to 2 decimal places, then divide back down before the 'int' function. ie, so 0.89 will become int(89/10), giving 8, while 0.899 would round to int(90/10), resulting in 9.

$\endgroup$
1
  • 1
    $\begingroup$ thanks Rich Sedman for your explanation. However the round() function actually do something slight different. If I take the rounded number, .84 and .86 will give me respectively .8 and .9 while in these cases I'll need to always get .8. This is a quite strange situation for me. I'm used to do programming and when I get a float number I've never had those problems. One solution could be use integer numbers (and so 1000 instead of 1.000), and change the equation accordingly but still, seems quite strange to me :). $\endgroup$
    – Tommaso
    Dec 29, 2021 at 10:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .