归一化变量的舍入值

时间:2014-07-18 22:50:01

标签: python decimal floating-accuracy

我试图在Python中编写一个函数,它给出了所需步数的规范化变量的值。我在舍入值并达到1时遇到问题。 由于我将在以后的计算中需要这些值,因此仅仅打印一定数量的小数就不够了。相反,我需要Python在0,0.00001,0.00002之类的计算中使用它们,依此类推,最多可达1 ...

这是代码....任何想法?我忘了提到我不想使用for循环......

只是为了说清楚...我使用递归函数来获取u 0->的值; 1后来使用berstain polynom来计算贝塞尔曲线/曲面。

from itertools import count
import sys

def b(u):

    if u>=0 and u<=1:
        u=count(0.0,0.001)
        u=u.next
        u=round(u.next(),4)   

        print(u)

        b(u)
    else:
        sys.exit(0)

b(0)

1 个答案:

答案 0 :(得分:0)

使用itertools中的count

>>> from itertools import count
>>> c = count(0.0, 0.0001)
>>> c.next()
0.0
>>> c.next()
0.0001
>>> c.next()
0.0002

count是一个无限的迭代器。因此,只要您继续.next(),它就会继续提供您的下一个号码。

请注意,由于浮动数字存储的有趣方式,您最终会在几百.next()次来电后达到此目的:

>>> c = count(0.0, 0.0001)
>>> ... (many .count() calls later)
>>> c.next()
0.9998999999999062
>>> c.next()
0.9999999999999062
>>> c.next()
1.0000999999999063

因此无论哪种方式,您都必须决定计算中真正需要的精度。例如,如果您只关注精度的4位小数:

>>> round(c.next(), 4)
0.0999
>>> round(c.next(), 4)
0.1
>>> round(c.next(), 4)
0.1001
>>> round(c.next(), 4)
0.1002
>>> round(c.next(), 4)
0.1003

如果使用迭代器,则不再需要其他函数。只需根据需要多次调用它即可获得您的号码范围:

>>> from itertools import count
>>> numbers = []
>>> c = count(0.0, 0.0001)
>>> how_many = 10
>>> while len(numbers) != how_many:
...   numbers.append(round(next(c), 4))
... 
>>> numbers
[0.0, 0.0001, 0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007, 0.0008, 0.0009]