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
Related
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)
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)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Assuming General formula of hyperbola to be y = 1 / (a*x + b), and we are provided with 100 data points out of which 99 points exactly fits a hyperbola and one data point is doesn't fits in it (unknown), from this information we need to find approximate values of a and b parameters for the hyperbola that will be formed from correct data points which are provided.
The approach which I took was by using scipy.optimize.curve_fit method as "parameters, _ = optimize.curve_fit(test, x_data ,y_data) "
where my "test" function was "def test(x, a, b): return 1 / (a*x + b)" using this method provides me perfect solution is my data points are all in first quadrant but if the data is distributed in more than one quadrant then this approach fails and I get wrong values of a and b.
Code:
import numpy as np
from scipy import optimize
x_data = np.linspace(-5,1, num=99)
y_data = 1 / (5 * x_data + 4) # value of original value of a = 5 & b = 4
np.random.seed(0)
# adding wrong point at 36th position
x_data = np.insert(x_data, 36 , 7)
y_data = np.insert(y_data, 36, 5)
def test(x, a, b):
return 1 / (a*x + b)
parameters, _ = optimize.curve_fit(test, x_data ,y_data)
[a,b] = parameters
a = 146.83956808191303
b = 148.78257639384725
# which is too wrong
Solution for above will certainly be appreciated.
Your problem is easy if the given points "exactly fit the hyperbola," and you need only two data points.
Your equation y = 1 / (ax + b) can be transformed into
(x*y) * a + (y) * b = 1
That is a linear equation in a and b. Use two data points to find the corresponding values of x * y and y and you end up with two linear equations in two variables (though in a and b rather than x and y). Then solve those two linear equations. This can easily be automated. This also does not depend on the quadrants of your two given points.
This does not work if your given points only approximate a hyperbola, of course.
In your last edit, you added the statement that only 99 of the points fit on the hyperbola, and one does not. This can be handled by choosing three pairs of your points (six distinct points), and finding the hyperbola that goes through each pair of points. That means calculating three hyperbolas (equivalently, calculating three values of a and b). If those three pairs of a and b all agree with small precision, the non-matching point was not in the chosen sample of three pairs of points and you have your hyperbola. If only two of them agree within precision, use that hyperbola. If no pair of the hyperbolas agree, some mistake was made and you should raise an exception.
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 4 years ago.
Improve this question
I have a particle trajectory in 1D, j=[] and for the time=np.arange(0, 10 + dt, dt) where dt is the time step. I have calculate the MSD according to this article.
I have searched in google as well as here for 1d MSD in python but did not find any suitable one as my python knowledge is very beginner level. I have written one code and it is working without any error but I am not sure that it represent the same thing according to the given article. Here is my code,
j_i = np.array(j)
MSD=[]
diff_i=[]
tau_i=[]
for l in range(0,len(time)):
tau=l*dt
tau_i.append(tau)
for i in range(0,(len(time)-l)):
diff=(j_i[l+i]-j_i[i])**2
diff_i.append(diff)
MSD_j=np.sum(diff_i)/np.max(time)
MSD.append(MSD_j)
Can anyone please check verify the code and give suggestion if it is wrong.
The code is mostly correct, here is a modified version where:
I simplified some expressions (e.g. range)
I corrected the average, directly using np.mean because the MSD is a squared displacement [L^2], not a ratio [L^2] / [T].
Final code:
j_i = np.array(j)
MSD = []
diff_i = []
tau_i = []
for l in range(len(time)):
tau = l*dt
tau_i.append(tau)
for i in range(len(time)-l):
diff = (j_i[l+i]-j_i[i])**2
diff_i.append(diff)
MSD_j = np.mean(diff_i)
MSD.append(MSD_j)
EDIT: I realized I forgot to mention it because I was focusing on the code, but the ensemble average denoted by <.> in the paper should, as the name implies, be performed over several particles, preferentially comparing the initial position of each particle with its new position after a time tau, and not as you did with a kind of time-running average
EDIT 2: here is a code that shows how to do a proper ensemble average to implement exactly the formula in the article
js = # an array of shape (N, M), with N the number of particles and
# M the number of time points
MSD_i = np.zeros((N, M))
taus = []
for l in range(len(time)):
taus.append(l*dt) # store the values of tau
# compute all squared displacements at current tau
MSD_i[:, l] = np.square(js[:, 0] - js[:, l])
# then, compute the ensemble average for each tau (over the N particles)
MSD = np.mean(MSD_i, axis=0)
And now you can plot MSD versus taus and Bob's your uncle
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.