numpy polynomial interpretation - python

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

Related

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]

Solve coupled differential equation using the function scipy.integrate.RK45

x' = f(x,y,t)
y' = g(x,y,t)
Initial conditions have been given as x0 and y0 with t0. Find the solution graph in the range t0 to a.
I have tried doing this for non-coupled equations but there seems to be a problem there as well. I have to solve this exactly using this function so other functions are not the options.
from numpy import *
from matplotlib import pyplot as plt
def f(t,x):
return -x
import scipy
from scipy import integrate as inte
solution = inte.RK45(f, 0 , [1] , 10 ,1, 0.001, e**-6)
print (solution)
I expect the output to be an array of all the values.
But <scipy.integrate._ivp.rk.RK45 at 0x1988ba806d8> is what I get.
You need to collect data with calling step() function:
from math import e
from scipy import integrate as inte
def f(t,x):
return -x
solution = inte.RK45(f, 0 , [1] , 10 ,1, 0.001, e**-6)
# collect data
t_values = []
y_values = []
for i in range(100):
# get solution step state
solution.step()
t_values.append(solution.t)
y_values.append(solution.y[0])
# break loop after modeling is finished
if solution.status == 'finished':
break
data = zip(t_values, y_values)
Output:
(0.12831714796342164, 0.879574381033538)
(1.1283171479634215, 0.3239765636806864)
(2.1283171479634215, 0.11933136762238628)
(3.1283171479634215, 0.043953720407578944)
(4.128317147963422, 0.01618962035012491)
(5.128317147963422, 0.005963176828962677)
(6.128317147963422, 0.002196436798667919)
(7.128317147963422, 0.0008090208875093502)
(8.128317147963422, 0.00029798936023261037)
(9.128317147963422, 0.0001097594143523445)
(10, 4.5927433621121034e-05)

Python plot only part of data

I want to plot any part or the data
here is the code
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
... ...
xs = []
avg = []
for line in lines:
if len(line) > 1:
x, y1 = line.split(',')
xs.append(float(x))
avg.append(float(y1))
ax1.plot(xs, avg, label='avg')
I added some of the code so you can see the type of the variables
I tried :
ax1.plot(xs[avg>0], avg[avg>0], label='avg')
and didnt work
im matlab i would do some thing like :
Indxs=find (ys>0)
Plot(xs(indxs),ys(indxs))
The syntax is correct. The problem is that xs and avg are no numpy arrays. So you first need to convert those lists to numpy arrays, then the slicing will work as expected.
xs = np.array(xs)
avg = np.array(avg)
ax1.plot(xs[avg>0], avg[avg>0], label='avg')
What you doesen't work since your index (avg > 0) in python is a boolean. When you are used to Matlab then you should definitely try numpy Boolean indexing.
you can do:
import numpy as np
xs = numpy.asarray(x)
ys = numpy.asarray(y)
ys_filtered = ys[x > 0]

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

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:
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]

Categories