具有大二项式系数的图函数 [英] Plot function with large binomial coefficients

查看:132
本文介绍了具有大二项式系数的图函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一个涉及二项式系数的函数.我的代码是

I would like to plot a function which involves binomial coefficients. The code I have is

#!/usr/bin/python
from __future__ import division
from scipy.special import binom
import matplotlib.pyplot as plt
import math

max = 500
ycoords = [sum([binom(n,w)*sum([binom(w,k)*(binom(w,k)/2**w)**(4*n/math.log(n)) for k in xrange(w+1)]) for w in xrange(1,n+1)]) for n in xrange(2,max)]

xcoords = range(2,max)

plt.plot(xcoords, ycoords)
plt.show()

不幸的是,这永远不会终止.如果将最大数量减少到40,则表示效果很好.有什么方法可以绘制此函数吗?

Unfortunately this never terminates. If you reduce max to 40 say it works fine. Is there some way to plot this function?

我还担心scipy.special.binom可能无法给出准确的答案,因为它似乎可以在浮点中工作.

I am also worried that scipy.special.binom might not be giving accurate answers as it works in floating point it seems.

推荐答案

通过使用numpy计算内部循环,可以显着提高速度.首先将max更改为N(因为max是内置的),然后将您的函数分解为更小,更易于管理的块:

You can get significant speedup by using numpy to compute the inner loop. First change max to N (since max is a builtin) and break up your function into smaller, more manageable chunks:

N = 500
X = np.arange(2,N)

def k_loop(w,n):
    K = np.arange(0, w+1)
    return (binom(w,K)*(binom(w,K)/2**w)**(float(n)/np.log(n))).sum()

def w_loop(n):
    v = [binom(n,w)*k_loop(w,n) for w in range(1,n+1)]
    return sum(v)

Y = [w_loop(n) for n in X]

使用N=300作为测试,需要使用3.932s和numpy代码,但是81.645s使用您的旧代码.由于您的旧代码花了这么长时间,我什至没有安排N=500案件的时间!

Using N=300 as a test it takes 3.932s with the numpy code, but 81.645s using your old code. I didn't even time the N=500 case since your old code took so long!

值得指出的是,您的函数基本上是指数增长的,可以这样近似.您可以在semilogx图中看到它:

It's worth pointing out that your function is basically exponential growth and can be approximated as such. You can see this in a semilogx plot:

这篇关于具有大二项式系数的图函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆