#🔒 Help needed with Newtons Method code

14 messages · Page 1 of 1 (latest)

austere atlas
#

Hi! So I'm not exactly an expert with Python, nor am I with Calculus, yet I tried to code a program that would work to solve Newtons Method. Nevertheless, even if the code seems alright, the answers that I am getting are not even close to the correct, checked answer. I believe it might be due to the fact that the program isn't taking into account the iterations and the change of the value of x when iterating. I was wondering if someone could please help me out with this? I really cannot see what the problem is and how to fix it. Thank you in advance!:

def newtonsmethod(ftn, fprime, x0, n):
    
    def f(x):
        return eval(ftn)
    
    def df(x):
        return eval(fprime)

    x=x0  

    for iterations in range(1,n+1):
        x = x - (f(x)/df(x))
    return x

n=100

ans=newtonsmethod("x**-2", "-2*x**-3", 1.4, 100)

print (f"The root was found to be at {ans} after {n} iterations")```
bronze thunderBOT
#

@austere atlas

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

hushed falcon
#

x^(-2) does not have any roots.

#

Using Newton's method on 1.4 would cause the number to grow to a huge positive, if I'm not wrong.

austere atlas
#

I thought it would be in fact a coding issue as its not an issue with the formulas itself, but with the iteration thing. maybe because I used a "for" instead of a "while" loop, although I don't really understand how I would do that :')?

hushed falcon
#

As I've told you, it's not an issue with the formula. It's that you used y = 1/x² which has no roots.

#

Try using y = 1/x² - 3 instead

austere atlas
#

that makes sense lol

#

thank you so much!!!

#

: )

#

!close

bronze thunderBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.