在 python 中使用 math.factorial(n) 计算阶乘有多少次 FLOP

How many FLOPs are there in calculating a factorial using math.factorial(n) in python

我试图了解如果我使用某种算法来查找指数近似和,特别是如果我在 python 中使用 math.factorial(n),那么会有多少 FLOP。我了解二元运算的 FLOP,那么阶乘在函数中也是二元运算吗?不是计算机科学专业的,我在这些方面有一些困难。我的代码如下所示:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import math



x = input ("please enter a number for which you want to run the exponential summation e^{x}")
N = input ("Please enter an integer before which term you want to turncate your summation")

function= math.exp(x)
exp_sum = 0.0
abs_err = 0.0
rel_err = 0.0



for n in range (0, N):
    factorial = math.factorial(n)            #How many FLOPs here?
    power     = x**n                         # calculates N-1 times
    nth_term  = power/factorial              #calculates N-1 times
    exp_sum   = exp_sum + nth_term           #calculates N-1 times
    abs_err   = abs(function - exp_sum)
    rel_err   = abs(abs_err)/abs(function)

请帮助我理解这一点。我对其他 FLOP 的看法也可能是错误的!

根据 SO answer and to the C source code,在 python2.7 中,math.factorial(n) 使用朴素算法计算阶乘,因此 它使用大约 n 个操作进行计算 作为阶乘 (n)=1*2*3*4*...*n.

关于其余部分的一个小错误是 for n in range(0,N) 将循环 N ,而不是 N-1 (来自 n=0n=N-1).

最后要注意的是,计算 FLOP 可能并不代表实际算法在现实世界中的性能,尤其是在 python 中,这是一种解释性语言,它倾向于将其大部分内部工作隐藏在巧妙的语法后面链接到已编译的 C 代码(例如:exp_sum + nth_term 实际上是 exp_sum.__add__(nth_term))。