0

I'm trying to find the root by Newton-Raphson method and encounter the following error in the while loop; other related questions deal with Sympy objects but the two variables involved in the error are not Sympy objects. Code below -

import math
import sympy as sym
import scipy, pylab
from sympy import Symbol, symbols
x=Symbol('x')
a=float(input("enter initial guess root"))
n=float(input("enter tolerance"))
def solve (x) : # function whose roots need to be found out
   return (x*math.tan(x) - math.sqrt(225-x*x)) 
def differ (a) : # function to differentiate 
   ans=sym.diff((x)*sym.tan(x) - sym.sqrt(225 - x*x))
   return (ans)      
i=2.0
while i > n : # standard Newton-Raphson condition **(causing error)**
        root=a-solve(a)/differ(a)
        i=abs(a-root)
        a=root
print (root) # print final root

Output with error -

enter initial guess root 2
enter tolerance 0.1
Traceback (most recent call last):
  File "try2.py", line 22, in <module>
    while i > n : 
  File "/Users/uditashukla/opt/anaconda3/lib/python3.8/site-packages/sympy/core/relational.py", line 384, in __nonzero__
    raise TypeError("cannot determine truth value of Relational")
TypeError: cannot determine truth value of Relational
user263315
  • 101
  • 2
  • 1
    [How do I format my code blocks?](https://meta.stackexchange.com/q/22186/628368) – khelwood Nov 17 '20 at 09:23
  • First, `differ()` takes argument `a` which is never been used inside the function. Second, if I do `print(type(i))` it outputs ``, so you are comparing a class with a floating point vaue. Maybe thats the reason for the error. – Tinu Nov 17 '20 at 09:39
  • @Tinu I understand your reasoning but why would 'i' be taken as a class when it's explicitly defined as a float i = 2.0 ? Thanks – user263315 Nov 17 '20 at 09:58
  • You redefine it here `i = abs(a - root)`, there it becomes a sympy class. I just printed the types of `a` and `root`, which are float and `sympy.core.add.Add`. I'm not too familiar with sympy, but I would guess if you like to evaluate the derivative numerically you need to do it differently. – Tinu Nov 17 '20 at 10:05

0 Answers0