Forum: Poser Python Scripting


Subject: Floating point decimals and binary representation.

structure opened this issue on Aug 24, 2021 ยท 17 posts


structure posted Tue, 24 August 2021 at 2:40 AM Forum Coordinator

so using the following code I came across the "can't represent this decimal properly" feature.

I understand the reasoning for this, it has to do with the fact that decimals cannot be accurately represented by binary.

But lets say I need real precision ( for some engineering venture perhaps ). The results in blue are what I want, the results in red are what I am getting.

Is there a workaround in python to actually return the decimals I want?

from os.path import basename, dirname, exists, isfile, join, splitext
...
...
# make a new ( numbered ) copy of the original file
def uniquify( path, ext ):
    file_name = path
    if isfile(file_name):
        expand = 0
        while True:
            expand += round( .1, 2 ) 
            exp = "_" + str(expand)
            new_file_name = file_name.split(ext)[0] + str(exp) + ext
            if isfile(new_file_name):
                continue
            else:
                return new_file_name

image.png


changing the .1 to 1/10 yields the same result

image.png

similarly the following code returns odd numbers also.

import numpy
for i in numpy.arange( 0.1, 0.9, 0.1 ):
    print( i )

which returns

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7000000000000001
0.8

if I round the result:

for i in numpy.arange( 0.1, 0.9, 0.1 ):
    print( round( i, 2 ) )

python returns the following ...

0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8

EDIT : a temporary workaround seems to be slicing the returned number like this

new_file_name = file_name.split(ext)[0] + str(exp[0:4]) + ext

Locked Out