How to create numpy arrays from list of numbers - python

I am learning numerical computing in python and tried the following code to integrate a function:
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

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]

Related

For loop alternitive to array subtraction

import numpy as np
x = np.array([[1,1,1],[2,2,2],[3,3,3]])
xt = np.array([1,2,3])
L = len(xt)
for i in range(0,L):
s = x-xt[i]
is there another way to get the same results without the use of a for loop, thanks.

How to use math function in Python

How to execute this code:
import numpy as np
import math
x = np.arange(1,9, 0.5)
k = math.cos(x)
print(x)
I got an error like this:
TypeError: only size-1 arrays can be converted to Python scalars
Thank you in advance.
So this is happening because math.cos doesn't accept numpy arrays larger than size 1. That's why if you had a np array of size 1, your approach would still work.
A simpler way you can achieve the result is to use np.cos(x) directly:
import numpy as np
x = np.arange(1,9, 0.5)
k = np.cos(x)
print(x)
print(k)
If you have to use the math module, you can try iterating through the array and applying math.cos to each member of the array:
import numpy as np
import math
x = np.arange(1,9,0.5)
for item in x:
k = math.cos(item)
print(k) # or add to a new array/list
You're looking for something like this?
import numpy as np
import math
x = np.arange(1,9, 0.5)
for ang in x:
k = math.cos(ang)
print(k)
You are trying to pass ndarray (returned by arange) to a function, which expects just real number. Use np.cos instead.
If you want pure-Python:
You can use math.fun in map like below:
import math
x = range(1,9)
print(list(map(math.cos, x)))
Output:
[0.5403023058681398, -0.4161468365471424, -0.9899924966004454, -0.6536436208636119, 0.2836621854632263, 0.9601702866503661, 0.7539022543433046, -0.14550003380861354]

numpy polynomial interpretation

I am using Polynomial.fit and get the following polynomial:
polynomial.str()
'0.8447708645677164 - 0.09751307764485126 x1 - 0.039531273903863295 x2'
but when I perform
polynomial(0),
it shows 0.9027526683087044.
But I thought if we input 0 into x, shouldn't it be 0.8447708645677164 instead?
This is the corrrect way
import numpy as np
p = [-0.039531273903863295, -0.09751307764485126, 0.8447708645677164 ]
val = np.polyval(p, 0)
print(val)
output
0.8447708645677164

Some problems with the arrays dimensions i guess

With this code i want to find a minimum in from a two dimensional function using the newton method:
from numpy import array
from numpy.linalg import solve, norm
def newton2d(f, df, x, tol=1e-12, maxit=50):
x = atleast_2d(x)
for i in range(maxit):
s = solve(df(x), f(x))
x -=s
if norm(s)<tol: print(x); print(i); break
f = lambda x: array([x[0]**2-x[1]**4, x[0]-x[1]**3])
df = lambda x: array([[2*x[0], -4*x[1]**3], [1, -3*x[1]**2]])
x = array([0.7, 0.7])
newton2d(f,df,x)
i think this code should work, but i get an error which goes as follows:
IndexError: index 1 is out of bounds for axis 0 with size 1
thanks for any help!!

NLopt minimize eigenvalue, Python

I have matrices where elements can be defined as arithmetic expressions and have written Python code to optimise parameters in these expressions in order to minimize particular eigenvalues of the matrix. I have used scipy to do this, but was wondering if it is possible with NLopt as I would like to try a few more algorithms which it has (derivative free variants).
In scipy I would do something like this:
import numpy as np
from scipy.linalg import eig
from scipy.optimize import minimize
def my_func(x):
y, w = x
arr = np.array([[y+w,-2],[-2,w-2*(w+y)]])
ev, ew=eig(arr)
return ev[0]
x0 = np.array([10, 3.45]) # Initial guess
minimize(my_func, x0)
In NLopt I have tried this:
import numpy as np
from scipy.linalg import eig
import nlopt
def my_func(x,grad):
arr = np.array([[x[0]+x[1],-2],[-2,x[1]-2*(x[1]+x[0])]])
ev, ew=eig(arr)
return ev[0]
opt = nlopt.opt(nlopt.LN_BOBYQA, 2)
opt.set_lower_bounds([1.0,1.0])
opt.set_min_objective(my_func)
opt.set_xtol_rel(1e-7)
x = opt.optimize([10.0, 3.5])
minf = opt.last_optimum_value()
print "optimum at ", x[0],x[1]
print "minimum value = ", minf
print "result code = ", opt.last_optimize_result()
This returns:
ValueError: nlopt invalid argument
Is NLopt able to process this problem?
my_func should return double, posted sample return complex
print(type(ev[0]))
None
<class 'numpy.complex128'>
ev[0]
(13.607794065928395+0j)
correct version of my_func:
def my_func(x, grad):
arr = np.array([[x[0]+x[1],-2],[-2,x[1]-2*(x[1]+x[0])]])
ev, ew=eig(arr)
return ev[0].real
updated sample returns:
optimum at [ 1. 1.]
minimum value = 2.7015621187164243
result code = 4

Categories