I have a function func(x). I want to know the x for func(x)-7=0. Because there is no exact real answer, I thought minimize would be a good idea.
from scipy.optimize import minimize
def func(x): # testing function which leads to the same behaviour
return (x * 5 + x * (1 - x) * (6-3*x) * 5)
def comp(x): # comparison function which should get zero
return abs(((func(x)) - 7))
x0 = 0.
x_real = minimize(comp, x0) # minimize comparison function to get x
print(x_real.x)
The last print gives me [ 0.7851167]. The following print...
print(comp(x_real.x))
print(comp(0.7851167))
...leads to different outputs:
[ 1.31290960e-08]
6.151420706146382e-09
Can someone explain me this behaviour?
EDIT: I think i understood your question wrong. Rounding the number as you did in the print statements obviously will result in some differences (which are pretty small (around 1e-9)).
To find all x, you should apply some global solution method or start from different intital point to find all local minimas(as seen in the plot).
The equation however has two solutions.
def func(x): # testing function which leads to the same behaviour
return (x * 5 + x * (1 - x) * (6-3*x) * 5)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.1,1,100)
plt.plot(x, func(x)-7)
plt.plot(x, np.zeros(100))
plt.show()
The function:
Related
I want to do a plot of this equation below:
Problem 1: You see... since my function is a function of ν I have to calculate my integral to each ν in my domain. My question is: what is the best way to do that?
I thought about using scipy to do the integral and a for loop to calculate it several times to each ν, but it seems a very inelegant way to solve my problem. Does someone know a better alternative? Does someone have a different idea?
Problem 2: When I write my code I get some errors, mainly because I think that the exponential has a very small expoent. Do you have any ideas of how should I change it so I can do this plot using Python?
Oh, if you try with a different method, it is supposed to look like this
Here is the code I was working on. I'm coming back to Python now, so maybe there is some errors. The plot I'm getting is very different from the one that this is supposed to look.
from scipy.integrate import quad
from scipy.constants import c, Planck, k, pi
import numpy as np
import matplotlib.pyplot as plt
def luminosity_integral(r, x):
T_est = 4000
R_est = 2.5 * (696.34*1e6)
Temp = ((2/(3*pi))**(1/4)) * T_est * ((R_est/r)**(3/4))
termo1 = ((4 * (pi**2) * Planck * (x**4) ) / (c**2))
termo2 = ((Planck * x) / (k*Temp))
return ((termo1 * r ) / (np.exp(termo2) - 1))
freqs = np.linspace(1e10, 1e16)
y = np.array([])
for i in freqs:
I = quad(luminosity_integral, (6 * 2.5 * (696.34*1e6)), (7e4 * 2.5 * (696.34*1e6)), args = (i))
temp = np.array([I[0]])
y = np.concatenate((y, temp))
plt.loglog(freqs, y)
plt.show()
Reuse the term R_est instead instead of writing its expression 3 times (better if you want to change that parameter).
you used a pi**2 in the constant multiplying the integral (don't affect the shape)
The shape resembles what you put as reference, but not in the suggested range.
You are using the value of T as T_*, are you sure about that?
Try this version of the code
from scipy.integrate import quad
from scipy.constants import c, Planck, k, pi
import numpy as np
import matplotlib.pyplot as plt
R_est = 2.5 * (696.34e6)
def luminosity_integral(r, x):
T_est = 4000
termo1 = ((4 * pi * Planck * (x**4) ) / (c**2))
termo2 = ((Planck * x) / (k*T_est)) * (3*pi/2 * (r/R_est)**3)**0.25
termo3 = np.exp(-termo2)
return ((termo1 * r ) * termo3 / (1 - termo3))
freqs = np.logspace(6, 16)
y = np.zeros_like(freqs)
for i, nu in enumerate(freqs):
y[i] = quad(luminosity_integral, (6* R_est), (7e4 * R_est), args = (nu))[0]
plt.loglog(freqs, y)
plt.ylim([1e6, 1e25])
plt.show()
I want to use fsolve to numerically find roots of a nonlinear transcendent equation.
The following code does this job.
import numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
kappa = 0.1
tau = 90
def equation(x, * parameters):
kappa,tau = parameters
return -x + kappa * np.sin(-tau*x)
x = np.linspace(-0.5,0.5, 35)
roots = fsolve(equation,x, (kappa,tau))
x_2 = np.linspace(-1.5,1.5,1500)
plt.plot(x_2 ,x_2 )
plt.plot(x_2 , kappa*np.sin(-x_2 *tau))
plt.scatter(x, roots)
plt.show()
I can double check the solutions graphically by plotting the two graphs f1(x)=x and f2(x)=k * sin(-x * tau), which i also included in the code.
fsolve gives me some wrong answers, without throwing any errors or convergence problems.
The Problem is, that I would like to automatize the procedure for varying kappa and tau, without me checking which answers are wrong and which are right. But with wrong answers as output, i can't use this method. Is there any other method or an option I can use, to be on the safe side?
Thanks for the help.
I couldn't run your code, there were errors and anyway, according to the documentation on scipy.fsolve, you're supposed to add an initial guess as the second input argument, not a range as what you did there fsolve(equation, x0, (kappa,tau))
You could of course however pass this in a loop, looping for every value in the array np.linspace(0.5, 0.5, 25). Although I do not understand what you are trying to achieve by varying kappa and tau, but if I take it that for those given parameters, you are interested in looking for the roots, here's how I would do it.
import numpy as np
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
# Take it as it is
kappa = 0.1
tau = 90
def equation(x, parameters):
kappa,tau = parameters
return -x + kappa * np.sin(-tau*x)
# Initial guess of x = -0.1
SolutionStack = []
x0 = -kappa
y = fsolve(equation, x0, [kappa, tau])
SolutionStack.append(y[0])
y = fsolve(equation, SolutionStack[-1], [kappa, tau])
SolutionStack.append(y[0])
deltaY = SolutionStack[-1] - SolutionStack[0]
# Define tolerance
tol = 5e-4
while ((SolutionStack[-1] <= kappa) and (deltaY <= tol)):
y = fsolve(equation, SolutionStack[-1], [kappa, tau])
SolutionStack.append(y[0])
deltaY = SolutionStack[-1] - SolutionStack[-2]
# Obviously a little guesswork is involved here, as it pertains to 0.07
if deltaY <= tol:
SolutionStack[-1] = SolutionStack[-1] + 0.07
# Obtaining the roots
Roots = []
Roots.append(SolutionStack[0])
for i in range(len(SolutionStack)-1):
if (SolutionStack[i+1] - SolutionStack[i]) <= tol:
continue
else:
Roots.append(SolutionStack[i+1]
Probably not the smartest way to do it (assuming I even understood you correctly), but perhaps you have an idea now.
I need tangent, arctangent functions for my Python program. I tried np.arctan and np.tan but observed a strange behaviour. In principle, the arctangent of tangent of some number is the number itself, but the code below doesn't give a precise value.
import numpy as np
x = 10
print(np.arctan(np.tan(x)))
When I change x to 2*x or 3*x, then the result is even more inaccurate.
I tried math.tan, math.atan but the result was the same.
Can someone please explain why it happens(which of the two functions is wrong), and under which condition one should be careful about using the arctangent and tangent functions?
three things to note:
in python (as in all programming languages i have ever looked at) trigonometric functions work with angles in radians i.e. the range [0, 2*pi) represents the 'full circle'
tan is periodic: tan(x) = tan(pi + x) (again note that this is in radians; in python tan(x) = tan(180 + x) will not be true!).
arctan returns a value in [-pi/2, pi/2).
in your example you fall back on the correct result in [-pi/2, pi/2):
import numpy as np
x = 10
print(np.arctan(np.tan(x))) # 0.575222039231
print(10 % (np.pi / 2)) # 0.5752220392306207
your function np.arctan(np.tan(x)) is equivalent to (the computationally less expensive)
def arctan_tan(x):
ret = x % np.pi
if ret > np.pi / 2:
ret -= np.pi
return ret
I have attempted to solve the following problem. I tried to solve it first with a set step size h using 0.1. However I need to change this in my code and use a for loop to loop through the values 0,1,..,20. I am a little confused how to do this problem but I was hoping to get some help with fixing the code I produced so far. Thanks!
import numpy as np
from math import sin
def derivative(func , x, h ):
for h in range(20):
return (func(x+h)-func(x))/h
def f(x):
return sin(x)
print(derivative(f, pi/4))
Gives the output
0.6706029729039897
MY EDIT:
def derivative(func , x, h ):
for h in range(20):
return (func(x+h)-func(x))/h
The exercise is asking you to compute the derivative using varying precision (represented using the variable h), and compare that to the exact/real derivative of the function.
Let h = 10 ^ -j, with j varying from 0 to 20. This means h will go (discretely) from 10⁻⁰ to 10⁻²⁰. You can use a for-loop and the range(...) function for that. Then pass that to the derivative function (to which you can a third parameter for the value of h)
def derivative(func, x, h):
return (func(x + h) - func(x)) / h
Next, you need to compare that to the exact derivative. The function f(x) = sin(x) has a known (exact) derivative which is cos(x). In math notation, d(sin x)/dx = cos x. This means that for any x, cos(x) will give you the exact derivative of sin at that x.
So you need to compare the result of the derivative(...) function to the value of cos(x). This will give you the difference. You can then use the basic Python function abs(x) to get the absolute value of that difference, which will give you the absolute difference, which is the desired result. Do that for each j from 0 to 20 and store the results somewhere, in an array or a dict.
from math import sin, cos, pi
x = pi / 4
diffs = {}
for j in range(21): # range is exclusive so range(21) will stop at 20
h = 10 ** -j
deriv = derivative(sin, x, h)
exact = cos(x)
diff = abs(deriv - exact)
diffs[h] = diff
Then, you can use pyplot's loglog function to plot those results on a graph, passing as X the range(...) result and as Y the array containing the results.
import matplotlib.pyplot as plt
ordered = sorted(diffs.items())
x, y = zip(*ordered)
plt.loglog(x, y)
So pretty much, I am aiming to achieve a function f(x)
My problem is that my function has an integral in it, and I only know how to construct definite integrals, so my question is how does one create an indefinite integral in a function (or there may be some other method I am currently unaware of)
My function is defined as :
(G is gravitational constant, although you can leave G out of your answer for simplicity, I'll add it in my code)
Here is the starting point, but I don't know how to do the integral portion
import numpy as np
def f(x):
rho = 5*(1/(1+((x**2)/(3**2))))
function_result = rho * 4 * np.pi * x**2
return function_result
Please let me know if I need to elaborate on something.
EDIT-----------------------------------------------------
I made some major progress, but I still have one little error.
Pretty much, I did this:
from sympy import *
x = Symbol('x')
rho = p0()*(1/(1+((x**2)/(rc()**2))))* 4 * np.pi * x**2
fooply = integrate(rho,x)
def f(rx):
function_result = fooply.subs({x:rx})
return function_result
Which works fine when I plug in one number for f; however, when I plug in an array (as I need to later), I get the error:
raise SympifyError(a)
sympy.core.sympify.SympifyError: SympifyError: [3, 3, 3, 3, 3]
(Here, I did print(f([3,3,3,3,3]))). Usually, the function returns an array of values. So if I did f([3,2]) it should return [f(3),f(2)]. Yet, for some reason, it doesn't for my function....
Thanks in advance
how about:
from sympy import *
x, p0, rc = symbols('x p0 rc', real=True, positive=True)
rho = p0*(1/(1+((x**2)/(rc))))* 4 * pi * x**2
fooply = integrate(rho,x)/x
rho, fooply
(4*pi*p0*x**2/(1 + x**2/rc),
4*pi*p0*rc*(-sqrt(rc)*atan(x/sqrt(rc)) + x)/x)
fooply = fooply.subs({p0: 2.0, rc: 3.0})
np_fooply = lambdify(x, fooply, 'numpy')
print(np_fooply(np.array([3,3,3,3,3])))
[ 29.81247362 29.81247362 29.81247362 29.81247362 29.81247362]
To plug in an array to a SymPy expression, you need to use lambdify to convert it to a NumPy function (f = lambdify(x, fooply)). Just using def and subs as you have done will not work.
Also, in general, when using symbolic computations, it's better to use sympy.pi instead of np.pi, as the former is symbolic and can simplify. It will automatically be converted to the numeric pi by lambdify.