Dylan Reynolds
Dylan Reynolds

Reputation: 11

Python sympy.Plot - OverflowError: int too large to convert to float

So i want to display the g function as a graph but whenever i run it, it returns the OverflowError in the title and i can't figure out why. Can anyone help?

%matplotlib inline 

import sympy as sym

def g(x):

   return 1 - (sym.factorial(365) / ((365 ** x) * sym.factorial(365 - x)))

sym.plot(f(x), (x, 0, 100), ylim=(0, 1))

Upvotes: 1

Views: 292

Answers (1)

asmeurer
asmeurer

Reputation: 91600

The problem is that in order to plot the function, SymPy uses NumPy to evaluate it numerically. NumPy is limited to machine precision floats, which can be no larger than ~10^309 (365! is ~10^778).

What you need to do is rewrite the expression so that it doesn't result in such large intermediary values. SymPy still needs some work to be able to help with this well.

We can use the identity:

  • binomial(n, x) = factorial(n)/(factorial(x - n)*factorial(x)

to replace factorial(365)/factorial(365 - x) with binomial(365, x)*factorial(x):

1 - binomial(365, x)*factorial(x)*365**-x

Which gives this plot

enter image description here

Upvotes: 1

Related Questions