Solving function containing gamma in Python - python

I'm quite new to programming with python.
I was wondering, if there is a smart way to solve a function, which includes a gamma function with a certain shape and scale.
I already created a function G(x), which is the cdf of a gamma function up to a variable x. Now I want to solve another function including G(x). It should look like: 0=x+2*G(x)-b. Where b is a constant.
My code looks like that:
b= 10
def G(x):
return gamma.cdf(x,a=4,scale=25)
f = solve(x+2*G(x)-b,x,dict=True)
How is it possible to get a real value for G(x) in my solve function?
Thanks in advance!

To get roots from a function there are several tools in the scipy module.
Here is a solution with the method fsolve()
from scipy.stats import gamma
from scipy.optimize import fsolve
def G(x):
return gamma.cdf(x,a=4,scale=25)
# we define the function to solve
def f(x,b):
return x+2*G(x)-b
b = 10
init = 0. # The starting estimate for the roots of f(x) = 0.
roots = fsolve(f,init,args=(b))
print roots
Gives output :
[9.99844838]
Given that G(10) is close to zero this solution seems likely
Sorry, I didn't take into account your dict=True option but I guess you are able to put the result in whatever structure you want without my help.

rom sympy import *
# from scipy.stats import gamma
# from sympy.stats import Arcsin, density, cdf
x, y, z, t, gamma, cdf = symbols('x y z t gamma cdf')
#sol = solve([x - 3, y - 1], dict=True)
from sympy.stats import Cauchy, density
from sympy import Symbol
x0 = Symbol("x0")
gamma = Symbol("gamma", positive=True)
z = Symbol("z")
X = Cauchy("x", x0, gamma)
density(X)(z)
print(density(X)(z))
sol = solve([x+2*density(X)(z)-10, y ], dict=True)
print(sol)
Or:
from scipy.stats import gamma
from sympy import solve, Poly, Eq, Function, exp
from sympy.abc import x, y, z, a, b
def G(x):
return gamma.cdf(x,a=4,scale=25)
b= 10
f = solve(x+2*G(x)-b,x,dict=True)
stats cdf gamma solve sympy

Related

Solving differential equations numerically

I tried solving a very simple equation f = t**2 numerically. I coded a for-loop, so as to use f for the first time step and then use the solution of every loop through as the inital function for the next loop.
I am not sure if my approach to solve it numerically is correct and for some reason my loop only works twice (one through the if- then the else-statement) and then just gives zeros.
Any help very much appreciatet. Thanks!!!
## IMPORT PACKAGES
import numpy as np
import math
import sympy as sym
import matplotlib.pyplot as plt
## Loop to solve numerically
for i in range(1,4,1):
if i == 1:
f_old = t**2
print(f_old)
else:
f_old = sym.diff(f_old, t).evalf(subs={t: i})
f_new = f_old + dt * (-0.5 * f_old)
f_old = f_new
print(f_old)
Scipy.integrate package has a function called odeint that is used for solving differential equations
Here are some resources
Link 1
Link 2
y = odeint(model, y0, t)
model: Function name that returns derivative values at requested y and t values as dydt = model(y,t)
y0: Initial conditions of the differential states
t: Time points at which the solution should be reported. Additional internal points are often calculated to maintain accuracy of the solution but are not reported.
Example that plots the results as well :
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# function that returns dy/dt
def model(y,t):
k = 0.3
dydt = -k * y
return dydt
# initial condition
y0 = 5
# time points
t = np.linspace(0,20)
# solve ODE
y = odeint(model,y0,t)
# plot results
plt.plot(t,y)
plt.xlabel('time')
plt.ylabel('y(t)')
plt.show()

Marginal density function with respect to X and Y in python

I have a joint density function in two variables x and y and I need to calculate marginal density function in X and Y using quad in python for function f(X, Y) = y*e**(-y(x+1))
from scipy.integrate import dblquad import numpy as np import math
def f(x,y):
return y*math.exp(-y(x+1)) # Joint Density Function
ans,err = dblquad(f,0,math.inf, lambda x: 0 , lambda x:math.inf)
ans
I am trying the above code in Jupyter notebook but for marginal density function, we need only limit for the integral of x and y the above code is throwing an error.
Maybe this will help you out
from sympy.abc import x,y
from sympy import integrate
fxy = y*e**((-y*x-y))
fy = integrate(fxy,(x,0,ifty))
fx = integrate(fxy,(y,0,ifty))
fy
fx
There is a typo error in your Joint Density Function f function. You missed one * for the product of -y and (x+1) in math.exp function. Fixing that typo error, your program should work.
def f(x, y):
return y*math.exp(-y*(x+1))

Evaluate numerically an equation with sympy

I want to ask something that provably is extremly easy but I didn't find how to do it... The point is that I want to define some function in python in a symbolic way using sympy in order to make its derivative and then use this expresion numerically.
Here an example is showed:
import numpy as np
from sympy import *
z = Symbol('z')
function = z*exp(z**2)
deriv = diff(function, z)
x = np.arange(1, 3, 0.1) #interval of points
#How can I evaluate numerically this array "x" with the function deriv???
Do you know how to do it? Thanks!
You can use lambdify with the numpy backend:
import numpy as np
from sympy import *
z = Symbol('z')
function = z*exp(z**2)
deriv = diff(function, z)
x = np.arange(1, 3, 0.1) #interval of points
d = lambdify(z, deriv, "numpy")
d(x)
# array([ 8.15484549e+00, 1.14689175e+01, 1.63762998e+01,
# 2.37373255e+01, 3.49286892e+01, 5.21825471e+01,
# 7.91672020e+01, 1.21994639e+02, 1.90992239e+02,
# 3.03860954e+02, 4.91383350e+02, 8.07886132e+02,
# 1.35069268e+03, 2.29681687e+03, 3.97320108e+03,
# 6.99317313e+03, 1.25255647e+04, 2.28335915e+04,
# 4.23706166e+04, 8.00431723e+04])

partial integration of a two dimensional gaussian function

I want to carry out the following partial integration of a 2-D gaussian function of four variables (x, y, alpha and beta), with respect to only x and y, as follows. In the end I want the answer to be a function of alpha and beta only.
I wrote the following code in python to execute the above mentioned integral.
from sympy import Symbol
from sympy import integrate
from math import e
alpha = Symbol('alpha')
beta = Symbol('beta')
x = Symbol('x')
y = Symbol('y')
n = 2
value = integrate( e**( -(x - alpha)**n - (y - beta)**n ), (x, -1, 1), (y, -1, 1) )
However I get the following error:
sympy.polys.polyerrors.DomainError: there is no ring associated with RR
The above mentioned integrate function works fine for n=1. However it breaks down for n>1.
Am I doing something wrong?
Welcome to SO!
Interestingly it works when you substitute alpha and beta into the integral bounds. Try:
from IPython.display import display
import sympy as sy
sy.init_printing() # LaTeX like pretty printing forIPython
alpha, beta, x, y = sy.symbols("alpha, beta, x, y", real=True)
f = sy.exp(-x**2 - y**2) # sy.exp() is better than the numeric constant
val = sy.integrate(f, (x, -1+alpha, 1+alpha), (y, -1+beta, 1+beta))
display(val)

How to define a one variable function from another multivariable function

I am trying to define a one variable g function from a multivariable function G:
def dG(thetaf,psi,gamma) :
return 0.35*(cos(psi))**2*(2*sin(3*thetaf/2+2*gamma)+(1+4*sin(gamma)**2)*sin(thetaf/2)-sin(3*thetaf/2))+sin(psi)**2*sin(thetaf/2)
g = lambda thetaf: dG(thetaf,psi,gamma)
unfortunately this is not working and the error i receive is that :
only length-1 arrays can be converted to Python scalars
You have to define some default values. If you do this by using keyword arguments, you don't even need to define a separate function.
from numpy import sin, cos, arange
def dG(thetaf,psi=0.5,gamma=1) :
return 0.35*(cos(psi))**2*(2*sin(3*thetaf/2+2*gamma)+(1+4*sin(gamma)**2)*sin(thetaf/2)-sin(3*thetaf/2))+sin(psi)**2*sin(thetaf/2)
thetaf = arange(10)
print dG(thetaf)
>>> [ 0.4902 0.1475 0.5077 1.6392 1.757 0.4624 -0.472 -0.2416 -0.2771 -1.3398]
You actually can define a separate function, but using keyword defaults is the cleaner alternative.
g = lambda tf: dG(tf, 0.5, 1)
g(thetaf)
array([ 0.4902, 0.1475, 0.5077, 1.6392, 1.757 , 0.4624, -0.472 ,
-0.2416, -0.2771, -1.3398])
Next time, please include the script in your original question in a nice format. It makes helping go faster.
I think it is just a simple mistake. You get theta and phi out of gamma and psi respectively, but then you never use them. Did you mean to use those as your parameters in g? If so, then it should look something like this
from numpy import sin, cos, arange, linspace, pi, zeros
import scipy.optimize as opt
def dG(thetaf, psi, gamma):
return 0.35*(cos(psi))**2*(2*sin(3*thetaf/2+2*gamma)+(1+4*sin(gamma)**2)*sin(thetaf/2)-sin(3*thetaf/2))+sin(psi)**2*sin(thetaf/2)
nt = 100
np = 100
gamma = linspace(0, pi/2, nt)
psi = linspace(0, pi/2, np)
x = zeros((nt, np))
for i, theta in enumerate(gamma):
for j, phi in enumerate(psi):
print('i = %d, j = %d') %(i, j)
g = lambda thetaf: dG(thetaf,phi,theta)
x[i,j] = opt.brenth(g,-pi/2,pi/2)

Categories