Ibelin
Ibelin

Reputation: 333

Why I can't get the result of 'r' in the equation with sympy?

I've defined the 'r' as the symbolic variable in the equation, but still get the error as "name 'r' is not defined"

from sympy import symbols, solve
#Total money you loan
A=1690*74
#Total month you need to pay
m=37
#Every month the total money you need to pay
x=4000
# r is the monthly interest rate
r=symbols('r')
expr=(A*r*(1+r)**m)/((1+r)**m-1)-x
sol=solve(expr,dict=True)
print(sol)

Run the file and get nothing feedback. What's wrong with the code?

Upvotes: 0

Views: 237

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14530

The equation you are trying to solve is (or can be rearranged to) a polynomial of order 37:

                37       
125060⋅r⋅(r + 1)         
────────────────── - 4000
         37              
  (r + 1)   - 1 

SymPy is trying hard to find an analytic solution to that but in general analytic solutions are only guaranteed to exist up to order 4 (and even then can be absurdly complicated).

I think what you really want here is a numeric solution so nsolve should do the job:

>>> nsolve(expr,r,1)
0.00915469685511422

As a fractional monthly interest rate that corresponds to an annualised rate (x100x12) of ~11%.

Upvotes: 1

Related Questions