How to convert the Matlab function code into Python code? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have been coding in Matlab for a few years and was recently switched to Python. How could I convert a Matlab function code into Python3 code as shown below?
function [estimates, model] = curvefitting(x, y, numOfpoint)
model = #expfun;
estimates = point(model, numOfpoint);
function [sse, FittedCurve] = expfun(params)
A = params(1);
B = params(2);
C = params(3);
FittedCurve = A*(x-B).^C;
ErrorVector = FittedCurve - y;
sse = sum(ErrorVector .^ 2);
end
end
What is #expfun meaning in python? How could I make model = #expfun work in python?

Instead of doing a line-by-line translation, I'd instead recommend using the tools available in Python. In this case if you are trying to perform a curve fit, first define your fit function
import numpy as np
def func(x, a, b, c):
return a * np.power(x - b, c)
Then you you use scipy.optimize.curve_fit
from scipy.optimize import curve_fit
# Assume these were already populated
x = np.array([...])
y = np.array([...])
# Perform curve fit
popt, pcov = curve_fit(func, x, y)
# Get fitted y-values at each x point
fit_y = func(x, *popt)

Related

Equations of motion in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 months ago.
Improve this question
Hello I am starting a mathematics projects about the motion of billiard balls on different domains, I am choosing to write a python code to describe the free motion of a ball on a polynomial domain:
Imagine bouncing a particle on the inside of a curve described by f(x) = x^4 for example;
I am struggling to put this into code and would appreciate any help you could give me.
Some useful information:
We take a ball with initial condition (x_0,v_0) where x_0 is the initial x position and v_0 is the slope at which we shoot the billiard.
The free motion of the billiard is described by the equations:
f(x_(j+1)) - f(x_j) = v_j(x_(j+1) - x_j) &
v_(j+1) = 2f'(x_(j+1)) - v_j,
This should give a polynomial in x which one can solve and then use the value of x to solve for v
I need to write a code that takes an initial condition, a function to describe a curve and its derivative that will spit out the values for x and v as the ball carries on along its path.
Please could anyone give me some tips on how to get started as my python skills are extremely limited and I'm struggling a lot more than I thought!
I will list my attempt below and the error it gave:
#equations of free motion
import numpy as np
def f(x): #function
return x^2
def df(x): #derivative of function
h = 1e-10
return (f(x+h) - f(x))/(2*h)
def free_motion(f,df,x0,v0):
x_j = x0
v_j = v0 #less than f'(x0)
f(x_jj) - (v_jj * (x_jj)) = f(x_j) - (v_j * (x_j)) #gives polynomial in x_jj
return x_jj,v_jj
Input In [11]
f(x_jj) - (v_jj * (x_jj)) = f(x_j) - (v_j * (x0)) #gives polynomial in x_jj
^
SyntaxError: cannot assign to operator

How to integrate a 3D function in Python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am writing a script that allows one to perform specific mathematical operations that involve integrals. For single integrals, I use scipy.integrate.quad. But there are cases where I want something to perform triple multivariable integrals like the following:
For the most part, there shouldn't be more than 3 variables, and I'm willing to work with something that doesn't go beyond triple integrals. Does anyone know any package, function or even script that could allow me to solve something like the equation shown?
Scipy's integrate module has scipy.integrate.dblquad and scipy.integrate.tplquad, which are very similar to the quad function you're already using, but allow double/triple integration.
To solve the equation shown, you could do something like the following:
from scipy import integrate
f = lambda x, y, z: ... # Some function to integrate
x1 = lambda y, z: ... # Lower boundary for x
x2 = lambda y, z: ... # Upper boundary for x
y1 = lambda z: ... # Lower boundary for y
y2 = lambda z: ... # Upper boundary for y
z1 = 0
z2 = 1
integral = integrate.tplquad(f, z1, z2, y1, y2, x1, x2)
print(integral)

How to fit math function to the dataset in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
I have three sets of data as shown below:
I wonder what is the function they follow and how to fit these curves in Python?
I guess the first function is something like:
y = axb + cx + d
I tried some arbitrary parameters:
x = numpy.arange(1,10000,2.)
a = 100.
b = -0.003
c = 50.
d = 0.1
y = -a/x**d+b*x+c
scatter(x,y)
The figure shows like this:
Anyone could help with the other two?
This is how I would solve this, as a total beginner with NumPy and SciPy:
First, create a Python function that we think calculates y for every x. (This equation is in the question above.)
def fx(x, a, b, c, d):
return -a / x**d + b*x + c
Then we need some data from the graph, which was not included in the question, so I guessed a bit, using the green graph in the question:
x = [0.01, 1000, 2000, 4000, 6000, 8000, 10000]
y = [1, 1.67, 1.75, 1.67, 1.6, 1.5, 1.4]
(x = 0 is an invalid point, since 0**d is 0, and we can't divide by zero. That's why I say "0.01" instead.)
Then we let SciPy calculate what the constants should be:
from scipy.optimize import curve_fit
popt, pcov = curve_fit(fx, x, y)
print(popt)
This results in "RuntimeError: Optimal parameters not found". We can help by manually guessing a value for d:
def fx(x, a, b, c):
d = -0.1
return -a / x**d + b*x + c
The popt variable will contain values for a, b, and c:
[-5.64063556e-01 -6.55610681e-05 6.41890483e-01]
It's helpful to use a graph calculator like Desmos when experimenting like this, and trying out different values.
There is a function in scipy that can be used to fit a function to data: scipy.optimize.curve_fit.
Thank for all your help. I got a solution from my friends.
y = -a/x**d+b*x+c
Since d makes the fit complicated, it will be easier to set d from 0.1 to 1.0, then use the curve_fit to fit the model. Finally find the best parameter set.

python - how to find area under curve? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
would like to ask if it is possible to calculate the area under curve for a fitted distribution curve?
The curve would look like this
I've seen some post online regarding the usage of trapz, but i'm not sure if it will work for a curve like that. Please enlighten me and thank you for the help!
If your distribution, f, is discretized on a set of points, x, that you know about, then you can use scipy.integrate.trapz or scipy.integrate.simps directly (pass f, x as arguments in that order). For a quick check (e.g. that your distribution is normalized), just sum the values of f and multiply by the grid spacing:
import numpy as np
from scipy.integrate import trapz, simps
x, dx = np.linspace(-100, 250, 50, retstep=True)
mean, sigma = 90, 20
f = np.exp(-((x-mean)/sigma)**2/2) / sigma / np.sqrt(2 * np.pi)
print('{:18.16f}'.format(np.sum(f)*dx))
print('{:18.16f}'.format(trapz(f, x)))
print('{:18.16f}'.format(simps(f, x)))
Output:
1.0000000000000002
0.9999999999999992
1.0000000000000016
Firstly, you have to find a function from a graph. You can check here. Then you can use integration in python with scipy. You can check here for integration.
It is just math stuff as Daniel Sanchez says.

Least square method in python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have two lists of data, one with x values and the other with corresponding y values. How can I find the best fit? I've tried messing with scipy.optimize.leastsq but I just can't seem to get it right.
Any help is greatly appreciated
I think it would be simpler to use numpy.polyfit, which performs Least squares polynomial fit. This is a simple snippet:
import numpy as np
x = np.array([0,1,2,3,4,5])
y = np.array([2.1, 2.9, 4.15, 4.98, 5.5, 6])
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
#plotting
import matplotlib.pyplot as plt
xp = np.linspace(-1, 6, 100)
plt.plot(x, y, '.', xp, p(xp))
plt.show()

Categories

Resources