Py学习  »  Python

python中的有效求和

Adam • 4 年前 • 2409 次点击  

WolframAlpha 能够计算出过高的n值: sum of sum

我有两种方法:a 对于

import numpy as np
import time

def summation(start,end,func):
    sum=0
    for i in range(start,end+1):
        sum+=func(i)
    return sum

def x(y):
    return y

def x2(y):
    return y**2

def mysum(y):
    return x2(y)*summation(0, y, x)

n=100

# method #1
start=time.time()
summation(0,n,mysum)
print('Slow method:',time.time()-start)

# method #2
start=time.time()
w=np.arange(0,n+1)
(w**2*np.cumsum(w)).sum()
print('Fast method:',time.time()-start)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/137545
文章 [ 5 ]  |  最新文章 4 年前