奇怪的功能行为(浮点问题)

时间:2019-05-23 20:46:14

标签: python math

为什么g(x)

from matplotlib import pyplot


if __name__ == '__main__':
    f = lambda n, d: sum([int(x) for x in str(d)*n])
    g = lambda k: sum([int(f(a,a)/a -1) for a in range(1,k)])/k

    a = [g(x) for x in range(1,100)]
    pyplot.plot(a)
    pyplot.show()

绘制此图? enter image description here

如果您这样做,它会变得更奇怪

    a = [g(i)/float(i) for i in range(1,100)]

enter image description here

1 个答案:

答案 0 :(得分:4)

显然,您使用的是Python 2.7,其中除法运算符将整数除以余数。更改g的定义:

def g(k):
    return sum([int(f(a, a) / float(a) - 1) 
                for a in range(1, k)]) / float(k)

enter image description here