How to integrate a 3D function in Python? [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 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)

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 convert the Matlab function code into Python code? [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 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)

Statistical regression on multi-dimensional data [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I have a set of data in (x, y, z) format where z is the output of some formula involving x and y. I want to find out what the formula is, and my Internet research suggests that statistical regression is the way to do this.
However, all of the examples I have found while researching only deal with two-dimensional data sets (x, y) which is not useful for my situation. Said examples also don't seem to provide a way to see what the resulting formula is, they just provide a function for predicting future outputs based on data not in a training data set.
The level of precision needed is that the formula for z needs to produce results within +/- 0.5 of actual values.
Can anyone tell me how I can do what I want to do? Please note I was not asking for specific recommendations on a software library to use.
If the formula is a linear function, checkout this tutorial. It uses Ordinary least squares to fit your data which is quite powerful.
Assume that you have data points (x1, y1, z1), (x2, y2, z2), ..., (xn, yn, zn), transform them into three separated numpy arrays X, Y and Z.
import numpy as np
X = np.array([x1, x2, ..., xn])
Y = np.array([y1, y2, ..., yn])
Z = np.array([z1, z2, ..., zn])
Then, use ols to fit them!
import pandas
from statsmodels.formula.api import ols
# Your data.
# Z = a*X + b*Y + c
data = pandas.DataFrame({'x': X, 'y': Y, 'z': Z})
# Fit your data with ols model.
model = ols("Z ~ X + Y", data).fit()
# Get your model summary.
print(model.summary())
# Get your model parameters.
print(model._results.params)
# should be approximately array([c, a, b])
If more variables are presented
Add as much variables in the DataFrame as you like.
# Your data.
data = pandas.DataFrame({'v1': V1, 'v2': V2, 'v3': V3, 'v4': V4, 'z': Z})
Reference
Python package StatsModel
The most basic tool you need to use is Multiple linear regression. The basic method models z as a linear function of x and y, added a Gaussian noise e on top of them: f(x,y) = a1*x + a2*y + a3 and then z is produced as f(x,y) + e, where e is usually a zero mean Gaussian with unknown variance. You need to find the coefficients a1,a2 and the bias a3, which are usually estimated with Maximum Likelihood, which then boils down to ordinary least squares under the Gaussian assumption. It has closed form analytic solution.
Since you have access to Python, take a look to linear regression in scikit-learn:
http://scikit-learn.org/stable/modules/linear_model.html#ordinary-least-squares
If you can reuse code from an existing a Python 3 tkinter GUI application on GitHub, take a look at fitting the linear polynomial surface equation that you mentioned using my tkInterFit project - it will also create fitted surface and contour plots. The GitHub source code is at https://github.com/zunzun/tkInterFit with a BSD license.

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.

Categories

Resources