使用python计算一个特殊的极限
Use python to calculate a special limit
我要计算这个表达式:
(1 + 1 / math.inf) ** math.inf,
其计算结果应为 e。然而 Python returns 1. 为什么会这样?
=====更新========
我想在这里做的是从用户的输入中推导出有效年利率,APR(年百分比率)。
def get_EAR(APR, conversion_times_per_year = 1):
return (1 + APR / conversion_times) ** conversion_times - 1
我希望这个表达式也适用于连续复利。是的,我知道我可以编写 if 语句来区分连续复利和正常情况(然后我可以直接使用常量 e
),但我更喜欢集成的方式。
因为您本质上是在执行两个单独的限制:
lim x->infty ((lim y->infty (1 + 1/y))^x)
其中 Python 正确计算为 1。
这是正确限制的穷人实现:
def euler(x):
return (1+1/x)**x
for i in range(10):
print(euler(10**i))
2.0
2.5937424601000023
2.7048138294215285
2.7169239322355936
2.7181459268249255
2.7182682371922975
2.7182804690957534
2.7182816941320818
2.7182817983473577
2.7182820520115603
我认为这里没有极限计算,因为这里没有变量可以在变量的不同值下计算整个语句。
Python 只是以最简单的方式进行计算。 Pythons 编译器简单地将 1/math.inf
转换为 0,然后计算 1 的 math.inf
次方作为 1
。
默认情况下 python 中未实现限制计算,为此您可以使用 sympy
from sympy import *
x= symbols('x')
r = limit((1+1/x)**x, x, oo)
print(r)
输出:
E
您可以在此处使用 mpmath (http://mpmath.org/) 包:
>>> import mpmath as mp
>>> f = lambda x: (1.0 + 1.0/x)**x
>>> mp.limit(f, mp.inf)
mpf('2.7182818284590451')
Python P.D.(tags/v3。D.A.:Hababakhs,2020 年 2 月,23:03:10)[Misk F.1916 64 verse (Ext. 4)] and croak
import sys
import math
E = sys.float_info.epsilon
e = (1 + E) ** (1 / E)
print(e, math.e, e == math.e)
OUTPUT:
2.718281828459045 2.718281828459045 True
我要计算这个表达式:
(1 + 1 / math.inf) ** math.inf,
其计算结果应为 e。然而 Python returns 1. 为什么会这样?
=====更新========
我想在这里做的是从用户的输入中推导出有效年利率,APR(年百分比率)。
def get_EAR(APR, conversion_times_per_year = 1):
return (1 + APR / conversion_times) ** conversion_times - 1
我希望这个表达式也适用于连续复利。是的,我知道我可以编写 if 语句来区分连续复利和正常情况(然后我可以直接使用常量 e
),但我更喜欢集成的方式。
因为您本质上是在执行两个单独的限制:
lim x->infty ((lim y->infty (1 + 1/y))^x)
其中 Python 正确计算为 1。
这是正确限制的穷人实现:
def euler(x):
return (1+1/x)**x
for i in range(10):
print(euler(10**i))
2.0
2.5937424601000023
2.7048138294215285
2.7169239322355936
2.7181459268249255
2.7182682371922975
2.7182804690957534
2.7182816941320818
2.7182817983473577
2.7182820520115603
我认为这里没有极限计算,因为这里没有变量可以在变量的不同值下计算整个语句。
Python 只是以最简单的方式进行计算。 Pythons 编译器简单地将 1/math.inf
转换为 0,然后计算 1 的 math.inf
次方作为 1
。
默认情况下 python 中未实现限制计算,为此您可以使用 sympy
from sympy import *
x= symbols('x')
r = limit((1+1/x)**x, x, oo)
print(r)
输出:
E
您可以在此处使用 mpmath (http://mpmath.org/) 包:
>>> import mpmath as mp
>>> f = lambda x: (1.0 + 1.0/x)**x
>>> mp.limit(f, mp.inf)
mpf('2.7182818284590451')
Python P.D.(tags/v3。D.A.:Hababakhs,2020 年 2 月,23:03:10)[Misk F.1916 64 verse (Ext. 4)] and croak
import sys
import math
E = sys.float_info.epsilon
e = (1 + E) ** (1 / E)
print(e, math.e, e == math.e)
OUTPUT:
2.718281828459045 2.718281828459045 True