【问题标题】:How many FLOPs are there in calculating a factorial using math.factorial(n) in python在 python 中使用 math.factorial(n) 计算阶乘时有多少 FLOP
【发布时间】:2016-09-20 05:32:33
【问题描述】:

如果我使用某种算法来查找指数近似和,我试图了解有多少 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 也有误!

【问题讨论】:

  • 您的代码存在一些问题:x 未定义,function= math.exp(x) 既不清楚也从未重复使用。你能澄清一下吗?
  • 我更新了我的代码,请看一下
  • 什么是典型的 N?最大 N 是多少?
  • 总和为 0 到 N-1,所以我将范围设置为 0 到 N,用户设置要完成多少次迭代,最大 N 可以是 v 非常大的数,接近无穷大.我尝试了 UpTo 200 进行研究。

标签: python-2.7 flops


【解决方案1】:

根据SO answerC 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))。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    相关资源
    最近更新 更多