BrainStorm
BrainStorm

Reputation: 2046

Weird function behaviour (floating point issue)

Why does 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()

Plot this? enter image description here

And it gets weirder and if you do

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

enter image description here

Upvotes: 0

Views: 50

Answers (1)

DYZ
DYZ

Reputation: 57033

Apparently you use Python 2.7 where the division operator divides integer numbers with a remainder. Change the definition of 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

Upvotes: 4

Related Questions