As a Python novice, you can overcome floating point mappings

Sorry for the long question and for the code, which is not entirely minimal.

I have a very limited understanding of the floating point comparisons. I read some python docs and tutorials on this topic. I have read some SO discussions, such as https://stackoverflow.com/a/312947/ .

However, I don’t know how to apply answers such as “why don’t you use str (value)” or “just format it with%” or “you should use decimal”. My favorite topic: "Just ignore the 11th decimal digits ... they don't matter much, and you can get the right aesthetics at the end if you format the answer as a string." I do not know how to make this work in my application.

Here is my code that might look like homework, but it really isn’t. I calculate the intersections of a grid of lines spanning a non-rectangular polygon. I create a rectangle, move one or more corners, then draw and redraw the grids on the polygon, so I need to calculate where the grid lines start, end and intersect.

def partition_boundaries(start, stop, number_of_partitions):
    interval = (stop - start)/number_of_partitions
    l = [start, stop]
    i = 1
    while i < number_of_partitions:
        l.insert(i, start + i*interval)
        i += 1
    return l

def test():
    test_cases = [
                  ((0.0, 1.0, 2), [0, .5, 1]), 
                  ((0.0, 1.0, 4), [0.0, 0.25, 0.5, 0.75, 1.0]), 
                  ]
    passes = 0
    for (args, expected_result) in test_cases:
        result = partition_boundaries(*args)
        if result != expected_result:
            print "Failed for: ", args, ".  Expected: ", expected_result, " Got: ", result
        else:
            passes = passes + 1
    print passes, " out of ", len(test_cases), " test cases passed."

test()

, : : (0.0, 1.0, 4). : [0,0, 0,25, 0,5, 0,7 5000000000000011, 1,0] : [0,0, 0,25, 0,5, 0,75, 1,0]

, , , .. " ", , , . , , "" "" .

.

, ?

+4
2

. Python, , , , True, , close , ,

def almost_equal(x,y):
    epsilon = 0.00001
    return abs(x-y) < epsilon

"" , almost_equal == .

+6

. , : 1) , ( 16). 2) , . Numpy :

import numpy as np

for p in range(-5,5):
     pp = 10**p
     print("{:6g}: {}".format(pp, np.spacing(pp)))

:

 1e-05: 1.69406589451e-21
0.0001: 1.35525271561e-20
 0.001: 2.16840434497e-19
  0.01: 1.73472347598e-18
   0.1: 1.38777878078e-17
     1: 2.22044604925e-16
    10: 1.7763568394e-15
   100: 1.42108547152e-14
  1000: 1.13686837722e-13
 10000: 1.81898940355e-12

, , 1 + 2.22044604925e-16 == 1 - False, 10 + 2.22044604925e-16 == 10 - True. @OldGeeksGuide, . . Numpy allclose()

0

Source: https://habr.com/ru/post/1534536/


All Articles