小编Phy*_*ist的帖子

在Python中实现Horner方法的问题

所以我用三种不同的方法写下了用于评估多项式的​​代码.霍纳的方法应该是最快的,而天真的方法应该是最慢的,对吗?但是,为什么计算它的时间不是我所期望的呢?对于itera和naive方法,计算时间有时会变得完全相同.它出什么问题了?

import numpy.random as npr
import time

def Horner(c,x):
    p=0
    for i in c[-1::-1]:
        p = p*x+i
    return p

def naive(c,x):
    n = len(c)
    p = 0
    for i in range(len(c)):
        p += c[i]*x**i 
    return p

def itera(c,x):
    p = 0
    xi = 1
    for i in range(len(c)):
        p += c[i]*xi
        xi *= x 
    return p

c=npr.uniform(size=(500,1))
x=-1.34

start_time=time.time()
print Horner(c,x)
print time.time()-start_time

start_time=time.time()
print itera(c,x)
print time.time()-start_time

start_time=time.time()
print naive(c,x)
print time.time()-start_time
Run Code Online (Sandbox Code Playgroud)

以下是一些结果:

[  2.58646959e+69]
0.00699996948242
[  2.58646959e+69]
0.00600004196167 …
Run Code Online (Sandbox Code Playgroud)

python iteration loops function polynomial-math

18
推荐指数
2
解决办法
3803
查看次数

在Python中同时执行两个类方法

我相信之前已经提出过许多类似的问题,但在阅读了很多类似的问题后,我仍然不太确定应该做些什么.所以,我有一个Python脚本来控制一些外部仪器(摄像头和功率计).我通过使用ctypes调用.dll文件中的C函数为两种乐器编写了类.现在它看起来像这样:

for i in range(10):
    power_reading = newport.get_reading(N=100,interval=1) # take power meter reading
    img = camera.capture(N=10)
    value = image_processing(img) # analyze the img (ndarray) to get some values
    results.append([power_reading,value]) # add both results to a list
Run Code Online (Sandbox Code Playgroud)

我想同时开始执行前两行.双方newport.get_readingcamera.capture需要100ms-1运行(他们会在同一时间运行,如果我选择了正确的参数).我不需要它们在同一时间完全启动,但理想情况下延迟应该小于总运行时间的大约10-20%(因此当每次运行时运行时间小于0.2秒).根据我的阅读,我可以使用该multiprocessing模块.所以我根据这篇文章尝试这样的事情:

def p_get_reading(newport,N,interval,return_dict):
    reading = newport.get_reading(N,interval,return_dict)
    return_dict['power_meter'] = reading

def p_capture(camera,N,return_dict):
    img = camera.capture(N)
    return_dict['image'] = img

for i in range(10):
    manager = multiprocessing.Manager()
    return_dict = manager.dict()
    p = multiprocessing.Process(target=p_capture, args=(camera,10))
    p.start()
    p2 = multiprocessing.Process(target=p_get_reading, args=(newport,100,1)) …
Run Code Online (Sandbox Code Playgroud)

python multiprocessing python-multithreading python-3.x python-multiprocessing

9
推荐指数
1
解决办法
1643
查看次数

如何在python中绘制没有曲线的单个点?

我想在绘图上绘制带有误差条的单个数据点,但我不想有曲线.我怎样才能做到这一点?是否有一些"隐形"线条样式,或者我可以将线条样式设置为无色(但标记仍然必须可见)?

所以这是我现在的图表:

plt.errorbar(x5,y5,yerr=error5, fmt='o')
plt.errorbar(x3,y3,yerr=error3, fmt='o')

plt.plot(x3_true,y3_true, 'r--', label=(r'$\lambda = 0.3$'))
plot(x5_true, y5_true, 'b--', label=(r'$\lambda = 0.5$'))

plt.plot(x5,y5, linestyle=':', marker='o', color='red') #this is the 'ideal' curve that I want to add
plt.plot(x3,y3, linestyle=':', marker='o', color='red')
Run Code Online (Sandbox Code Playgroud)

我的图表

我想保留两条虚曲线,但我不想要两条虚线曲线.我怎样才能做到这一点?如何更改标记的颜色,以便红色曲线的红点,蓝色曲线的蓝点?

python plot curve linestyle

7
推荐指数
1
解决办法
2万
查看次数

将cProfile结果保存到可读的外部文件中

我正在cProfile尝试尝试分析我的代码:

pr = cProfile.Profile()
pr.enable()
my_func()   # the code I want to profile
pr.disable()
pr.print_stats()
Run Code Online (Sandbox Code Playgroud)

但是,结果太长,无法在Spyder终端中完全显示(看不到运行时间最长的函数调用...)。我也尝试使用保存结果

 cProfile.run('my_func()','profile_results')
Run Code Online (Sandbox Code Playgroud)

但是输出文件的格式不是人类可读的格式(尝试使用带.txt后缀和不带后缀)。

所以我的问题是如何将分析结果保存到人类可读的外部文件中(例如以.txt正确显示所有单词的格式)?

python text profiling cprofile python-3.x

6
推荐指数
4
解决办法
3928
查看次数

如何使用Python内置函数odeint求解微分方程?

我想用给定的初始条件求解这个微分方程:

(3x-1)y''-(3x+2)y'+(6x-8)y=0, y(0)=2, y'(0)=3
Run Code Online (Sandbox Code Playgroud)

ans应该是

y=2*exp(2*x)-x*exp(-x)

这是我的代码:

def g(y,x):
    y0 = y[0]
    y1 = y[1]
    y2 = (6*x-8)*y0/(3*x-1)+(3*x+2)*y1/(3*x-1)
    return [y1,y2]

init = [2.0, 3.0]
x=np.linspace(-2,2,100)
sol=spi.odeint(g,init,x)
plt.plot(x,sol[:,0])
plt.show()
Run Code Online (Sandbox Code Playgroud)

但我得到的不同于答案.我做错了什么?

python numpy scipy differential-equations odeint

5
推荐指数
1
解决办法
3万
查看次数

如何改善这种自适应梯形法则?

我已经尝试过由纽曼(Newman)编写的计算物理学进行练习,并为自适应梯形规则编写了以下代码。当每张幻灯片的误差估计值大于允许值时,它将把该部分分成两半。我只是想知道我还能做些什么来使算法更有效。

xm=[]
def trap_adapt(f,a,b,epsilon=1.0e-8):    
    def step(x1,x2,f1,f2):
        xm = (x1+x2)/2.0
        fm = f(xm)
        h1 = x2-x1
        h2 = h1/2.0
        I1 = (f1+f2)*h1/2.0
        I2 = (f1+2*fm+f2)*h2/2.0
        error = abs((I2-I1)/3.0) # leading term in the error expression
        if error <= h2*delta:
            points.append(xm) # add the points to the list to check if it is really using more points for more rapid-varying regions
            return h2/3*(f1 + 4*fm + f2)
        else:
            return step(x1,xm,f1,fm)+step(xm,x2,fm,f2) 
    delta = epsilon/(b-a)
    fa, fb = f(a), f(b)  
    return step(a,b,fa,fb)
Run Code Online (Sandbox Code Playgroud)

此外,我使用了一些简单的公式将其与Romberg积分进行比较,发现对于相同的精度,该自适应方法使用更多的点来计算积分。

仅仅是因为其固有的局限性吗?使用这种自适应算法代替Romberg方法有什么优势?有什么方法可以使其更快,更准确?

python algorithm recursion numerical-methods numerical-integration

5
推荐指数
1
解决办法
1514
查看次数

如何找到图像中亮点的中心?

这是我将要处理的各种图像的示例:

球http://pages.cs.wisc.edu/~csverma/CS766_09/Stereo/callight.jpg

每个球都有一个亮点.我想找到亮点中心的坐标.我怎么能用Python或Matlab做到这一点?我现在遇到的问题是,当场不止一个点具有相同(或大致相同)的白色,但我需要的是找到白点的"簇"的中心.

另外,对于最左边和最右边的图像,我如何找到整个圆形物体的中心?

python search matlab image image-processing

5
推荐指数
1
解决办法
4927
查看次数

如何在python中创建3D高度图

我有一个二维数组Z,用于存储该元素位置的高度。除了使用此处需要创建与Z大小相同的数组X和Y的方法外,还有没有更简单的方法来创建3D高度图?

3D表面高度图类似于此处的第一个表面图。

python 3d plot matplotlib surface

5
推荐指数
2
解决办法
5630
查看次数

在matlab中使用fft,ifft和fftshift

我试图实现分步傅立叶方法来解决光学中的非线性薛定谔方程.它主要分别处理线性部分和非线性部分.它通过傅里叶变换和时域中的非线性部分来求解线性部分.

从书中复制以下代码:

alpha = 0
beta_2 = 1
gamma = 1

T = linspace(-5,5,2^13);
delta_T = T(2)-T(1);

L = max(size(A));
delta_omega = 1/L/delta_T*2*pi;
omega = (-L/2:1:L/2-1)*delta_omega;

A = 2*sech(T);
A_t = A;
step_num = 1000;
h = 0.5*pi/step_num;
results = zeros(L,step_num);

A_f = fftshift(fft(A_t));
for n=1:step_num
    A_f = A_f.*exp(-alpha*(h/2)-1i*beta_2/2*omega.^2*(h/2));
    A_t = ifft(A_f);
    A_t = A_t.*exp(1i*gamma*(abs(A_t).^2*h));
    A_f = fft(A_t);
    A_f = A_f.*exp(-alpha*(h/2)-1i*beta_2/2*omega.^2*(h/2));
    A_t = ifft(A_f);
    results(:,n) = abs(A_t);
end
Run Code Online (Sandbox Code Playgroud)

A_t脉冲在哪里(要解决的功能).我不明白的是,它最初用于fftshift将零频率移动到中心,但后来又在循环中没有fftshift.我尝试添加fftshift到主循环,或在最开始删除它.两者都给出了错误的结果,为什么呢?在一般情况下,我应该什么时候使用fftshift和 …

matlab fft numerical-methods ode ifft

5
推荐指数
1
解决办法
819
查看次数

如何在cython中的函数参数中键入函数

我已经做了一个在python中进行优化的函数(我们称之为optimizer)。它要求将函数objective作为函数参数之一进行优化(我们称之为)。objective是一个接受一维np.ndarray并返回float数字的函数(与doubleC ++中的函数相同)。

我已经阅读了这篇文章,但是我不确定它是否实际上与我的问题以及使用时的问题相同ctypedef int (*f_type)(int, str),但是Cannot convert 'f_type' to Python object在编译过程中会出现错误。它仅适用于C函数吗?如何输入python函数?

编辑:我的代码是什么样的:

cpdef optimizer(objective, int num_particle, int dim,
             np.ndarray[double, ndim=1] lower_bound,
             np.ndarray[double, ndim=1] upper_bound):

    cdef double min_value
    cdef np.ndarray[double, ndim=2] positions = np.empty((num_particle,dim), dtype=np.double)
    cdef np.ndarray[double, ndim=1] fitness = np.empty(num_particle, dtype=np.double)
    cdef int i, j

    # do lots of stuff not shown here
    # involve the following code:
    for i in range(num_particle): …
Run Code Online (Sandbox Code Playgroud)

python static-typing cython

4
推荐指数
1
解决办法
591
查看次数