S.Smith
S.Smith

Reputation: 55

How to put an integral in a function in python/matplotlib

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 :

enter image description here

(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

Upvotes: 2

Views: 1392

Answers (2)

asmeurer
asmeurer

Reputation: 91500

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.

Upvotes: 0

f5r5e5d
f5r5e5d

Reputation: 3706

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]

Upvotes: 2

Related Questions