如果我使用某种算法来找到指数近似和,我试图理解有多少FLOP,特别是如果我在python中使用math.factorial(n)。我理解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!
答案 0 :(得分:1)
根据SO answer和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=0
到{{1} })。
最后要注意的是,计算FLOP可能无法代表实际算法的真实世界性能,特别是在python中,这是一种解释性语言,并且它往往隐藏其大部分内部工作背后的巧妙语法链接到已编译的C代码(例如:n=N-1
是实际的exp_sum + nth_term
)。