[英]How to create numpy arrays from list of numbers
I am learning numerical computing in python and tried the following code to integrate a function: 我正在学习python中的数值计算,并尝试了以下代码来集成函数:
import numpy as np
import scipy.integrate as spi
def integration(z):
if np.isscalar(z):
y, err = spi.quad(lambda x: 1/np.sqrt(1+x),0,z)
" spi.quad returns integrated value with error"
print y # result for scalar input
else:
for x in z:
y, err = spi.quad(lambda x: 1/np.sqrt(1+x),0,x)
print y # result for arrays
return
But the result I get is not an array I need an array for further computation. 但是我得到的结果不是一个数组,我需要一个数组来进行进一步的计算。 I get the following result:
我得到以下结果:
z = np.linspace(0,1,10)
>>> integration(z)
0.0
0.108185106779
0.21108319357
0.309401076759
0.403700850309
......
Any help here how should I modify my code to get numpy array 这里的任何帮助我应该如何修改我的代码以获取numpy数组
Simple 简单
import numpy as np
import scipy.integrate as spi
def integration(z):
if np.isscalar(z): z = np.asarray([z])
y = np.empty_like(z)
for i in range(z.shape[0]):
y[i], err = spi.quad(lambda x: 1/np.sqrt(1+x),0,z[i])
return y
Test: 测试:
>>> z = np.linspace(0,1,10)
>>> intg_z = integration(z)
>>> print intg_z
[ 0. 0.10818511 0.21108319 0.30940108 0.40370085 0.49443826
0.5819889 0.66666667 0.74873708 0.82842712]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.