Issue with implementing sympy into newtons method

Question:

I was trying to make a calculator for newtons method given a function, I’ve got everything down except that I keep running into an issue when I’m trying to do log of a different base or ln(x).

I’d appreciate the help!

import sympy as sp


x = sp.symbols('x')

# ask for expression and initial guess
expression = input('input function: ')
initial = float(input('input an initial guess: '))
iterate = int(input('input how many times you want it to iterate: '))


# find derivative of function
f_prime = sp.diff(expression, x)

f = sp.lambdify(x, expression, 'numpy')
df = sp.lambdify(x, f_prime, 'numpy')


# newtons method rounded to 8 decimal places
for i in (1, iterate):
    i = initial - (f(initial)/df(initial))
    initial = round(i, 8)

print(f'The root is {initial} after {iterate} iterations')

Everytime I put in log of a different base it would give me

TypeError: return arrays must be of ArrayType or a name error

for ln(x) it would give me

AttributeError: 'Symbol' object has no attribute 'ln'. Did you mean: 'n'?
Asked By: Geegee

||

Answers:

The output of your expression = input('input function: ') is of type string. Before creating f = sp.lambdify(...) you need to convert that expression into a symbolic expression. sympify is the command you need to use:

expression = sp.sympify(input('input function: '))
Answered By: Davide_sd
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.