在python中计算物理公式的有效/巧妙方式

我正在寻找一种有效的方法来计算(复杂)数学函数的结果。

现在,它看起来可与:

def f(x):
    return x**2
def g(x):
    if x is 0: return 1
    return f(x)*5
def h(x):
    return g(x)

res = [f(input[i]) for i in range(1000000)]

由于每个函数调用在Python中都代价高昂,因此如果f(x)与g(x)合并,则代码应该已经运行得更快。不幸的是,在那种情况下,g(x)函数的'return ...'行已经很长了。此外,当前实际上总共定义了6个函数,因此完整的公式占用几行。

那么,计算物理公式结果的巧妙方法是什么?

评论
Orz
Orz

If you're concerned about the length of the return ... line you could use intermediate values, e.g.:

def f(x):
    return x**2
def g(x):
    if x == 0:
        return 1
    x_squared = x ** 2
    return x_squared * 5

In this context, it is incorrect to use the is operator as in x is 0. It does not check for numerical equality, which is what == does. The is operator checks that the two operands refer to exactly the same object in memory, which happens to be true in this case because the Python interpreter is intelligently reusing number objects. It can lead to confusing errors, for example:

a = 1234
b = 1233
a is (b + 1) # False

In practice, is is mainly used only to check if a value is None.

点赞
评论