Reputation: 233
def nu(r):
'''Returns the stellar density function.'''
return 1 / ( r * (1 + (r / a))**3)
mass_int = lambda r: 4 * r**2 * nu(r)
print(mass_int(0))
This gives me a divide by zero error, presumably because of the 1/r term being evaluated in isolation. Is using sympy to form the correct algebraic expression the only way around this? Seems absurd.
Upvotes: 1
Views: 791
Reputation: 15397
This isn't a python question, or even a computer programming question. It's simple math.
f(x) = 1 / (x * (1 + x/a)**3)
g(x) = 4x**2
h(x) = 4x / (1 + x/a)**3
Is there a difference between f(g(r)) and h(r)? Of course there is. Even though the plots look exactly the same, f(g(0)) is undefined, and on a plot must show as a point discontinuity.
As an intelligent user of this function, you can recognize that the point discontinuity is there. If you choose, you can replace f(g(r)) with h(r). The only difference will be the desired one of having the function defined at 0.
Math doesn't do that on its own, and no programming language will reduce the function composition for you on its own, unless you ask it to, because you are the user, and you're supposed to know what you want from a program. If you create a function composition that has a point discontinuity, it's expected that you did so for a reason. The intelligence is expected to be in the programmer, not in the compiler. Either compose and reduce the function by yourself, or do something like having sympy do it. Either way, it's up to you to make it explicit to the computer that these two functions should be related to each other.
Upvotes: 0
Reputation: 36043
It's not doing anything wrong. Given r = 0
:
1 / ( r * (1 + (r / a))**3)
= 1 / ( 0 * (1 + (0 / a))**3)
= 1 / ( 0 * (1 + 0 )**3)
= 1 / ( 0 * 1 **3)
= 1 / ( 0 * 1 )
= 1 / 0
So when you ask for nu(0)
you get an error. It doesn't look ahead and do special algebra things, it just throws the error. Python is not magic, it's not absurd that you'd need sympy for this.
I suggest you just add a special case to mass_int
for r == 0
.
Upvotes: 4