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'?
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: '))