Python sympy.Plot - OverflowError:int太大而无法转换为float

时间:2021-09-07 10:22:34

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?

所以我想将g函数显示为图形,但每当我运行它时,它会返回标题中的OverflowError,我无法弄清楚原因。有人可以帮忙吗?

%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))

1 个解决方案

#1


1  

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).

问题是,为了绘制函数,SymPy使用NumPy以数字方式对其进行评估。 NumPy仅限于机器精度浮标,其不大于~10 ^ 309(365!~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.

您需要做的是重写表达式,使其不会产生如此大的中间值。 SymPy仍然需要一些工作才能很好地帮助这个。

We can use the identity:

我们可以使用身份:

  • binomial(n, x) = factorial(n)/(factorial(x - n)*factorial(x)
  • 二项式(n,x)=阶乘(n)/(阶乘(x - n)*阶乘(x)

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

用二项式(365,x)* factorial(x)替换factorial(365)/ factorial(365 - x):

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

Which gives this plot

这给了这个情节

Python sympy.Plot  -  OverflowError:int太大而无法转换为float

#1


1  

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).

问题是,为了绘制函数,SymPy使用NumPy以数字方式对其进行评估。 NumPy仅限于机器精度浮标,其不大于~10 ^ 309(365!~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.

您需要做的是重写表达式,使其不会产生如此大的中间值。 SymPy仍然需要一些工作才能很好地帮助这个。

We can use the identity:

我们可以使用身份:

  • binomial(n, x) = factorial(n)/(factorial(x - n)*factorial(x)
  • 二项式(n,x)=阶乘(n)/(阶乘(x - n)*阶乘(x)

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

用二项式(365,x)* factorial(x)替换factorial(365)/ factorial(365 - x):

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

Which gives this plot

这给了这个情节

Python sympy.Plot  -  OverflowError:int太大而无法转换为float