Marginal density function with respect to X and Y in python - 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))

Related

How to resolve integration function not integrating correctly?

I am trying to build a few simple operations such as a derivative and integral function to operate on lambda functions because sympy and scipy were struggling to integrate some things that I was passing to them.
The derivative function does not give me any issues and looks to return the derivative of the input function when plotted, but the integral function does not return the same, and does not plot the correct integral of the input.
import matplotlib.pyplot as plt
import numpy as np
from phys_func import func
sr = [-10,10]
x = np.linspace(sr[0],sr[1], 100)
F = lambda x: x**2
f = func.I(F,x)
plt.plot(x,F(x), label = 'F(x)')
plt.plot(x,f(x), label = 'f(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
The integration function that does not work:
def I(F,x):
dx = (x[len(x)-1] - x[0])/len(x)
return lambda x : 0.5*( F(x+dx) + F(x) )*dx
The derivative function that works:
def d(f,x):
dx = (x[len(x)-1]-x[0])/len(x)
return lambda x: (f(x+dx)-f(x))/dx
Can anyone lend me a hand please?
You cannot find the anti derivative of a function numerically with out knowing the value of the anti derivative at a single point. Suppose if you fix the value of the antiderivative function value at x =a to be 0 (and given function is continuous from [a,x]) , then we can use definite integrals. For this function, let us take a=0 (i.e 0 is a root of anti derivative function), so you can do a definite integral from [0,x]. Also, your integration function is wrong. You need to sum all the 0.5*( F(x+dx) + F(x) )*dx elements from 0 to x to get the definite integral.
You can modify I(f,x) as follows
def I(F1): # N is number of intervals
return lambda x, N: np.sum( 0.5*( F1(np.linspace(0,x,num=N)+ (x)/N ) + F1(np.linspace(0,x,num=N)))*(x)/N)
In [1]: import numpy as np
In [2]: def I(F1): # N is number of intervals
...: return lambda x, N: np.sum( 0.5*( F1(np.linspace(0,x,num=N)+ (x)/N
...: ) + F1(np.linspace(0,x,num=N)))*(x)/N)
...:
In [3]: F = lambda x: x**2
In [4]: x_ran = np.linspace(-10,10, 100)
In [5]: y = I(F)
In [6]: y_ran = []
In [7]: for i in x_ran:
...: y_ran.append(y(i,100))
In [8]: plt.plot(x_ran,y_ran)
In [9]: plt.show()

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()

Solving function containing gamma in 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

Is fsolve good to any system of equations?

I don't have a lot of experience with Python but I decided to give it a try in solving the following system of equations:
x = A * exp (x+y)
y = 4 * exp (x+y)
I want to solve this system and plot x and y as a function of A.
I saw some a similar question and give fsolve a try:
`from scipy.optimize import fsolve
def f(p):
x, y = p
A = np.linspace(0,4)
eq1= x -A* np.exp(x+y)
eq2= y- 4* np.exp(x+y)
return (eq1,eq2)
x,y = fsolve(f,(0, 0))
print(x,y)
plt.plot(x,A)
plt.plot(y,A)
`
I'm getting these errors:
setting an array element with a sequence.
Result from function call is not a proper array of floats.
Pass the value of A as argument to the function and run fsolve for each value of A separately.
Following code works.
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
import numpy as np
def f(p,*args):
x, y = p
A = args[0]
return (x -A* np.exp(x+y),y- 4* np.exp(x+y))
A = np.linspace(0,4,5)
X = []
Y =[]
for a in A:
x,y = fsolve(f,(0.0, 0.0) , args=(a))
X.append(x)
Y.append(y)
print(x,y)
plt.plot(A,X)
plt.plot(A,Y)
4.458297786441408e-17 -1.3860676807976662
-1.100088440495758 -0.5021704548996653
-1.0668987418054918 -0.7236105952221454
-1.0405000943788385 -0.9052366768954621
-1.0393471472966025 -1.0393471472966027
/usr/local/lib/python3.6/dist-packages/scipy/optimize/minpack.py:163: RuntimeWarning: The iteration is not making good progress, as measured by the
improvement from the last ten iterations.
warnings.warn(msg, RuntimeWarning)
/usr/local/lib/python3.6/dist-packages/scipy/optimize/minpack.py:163: RuntimeWarning: The iteration is not making good progress, as measured by the
improvement from the last five Jacobian evaluations.
warnings.warn(msg, RuntimeWarning)
[<matplotlib.lines.Line2D at 0x7f4a2a83a4e0>]

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)

Categories