Question

Problem 4. PYTHON: (Root Finding) Write a program root.py (a variant of the sqrt.py program we...

Problem 4. PYTHON: (Root Finding) Write a program root.py (a variant of the sqrt.py program we discussed in class) that accepts k (int), c (float), and epsilon (float) as command-line arguments, and writes to standard output the kth root of c, up to epsilon decimal places.

Example: $ python3 root . py 3 2 1e -15

1.2599210498948732

Hints:

Set t (our guess) to c

Use the condition |1 − c/tk| > to continue the loop

At each iteration, replace the estimate t by t − f(t)/f0 (t), where f(t) = t k − c and f 0 (t) = ktk−1

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The method described in the question is called Newton Raphson method. Below is the python code for the question. Copy it to a file called "root.py" and run it through command line as "python3 root.py 3 2 1e-15".

import sys

# Read command line arguments
args = sys.argv
k = int(args[1])
c = float(args[2])
e = float(args[3])

# At any iteration, 't' will hold the current iteration's guess and 'prev_t' will hold the previous iteration's guess
t = c
while True:
   prev_t = t
   ft = t**k - c
   f0t = k*(t**(k-1))
   t = t - ft/f0t
  
   # If absolute differnt of previous guess and current guess is less than equal to epsilon, then we have found our answer
   if abs(prev_t - t) <= e:
       break

print("The answer is: {}".format(t))

Add a comment
Know the answer?
Add Answer to:
Problem 4. PYTHON: (Root Finding) Write a program root.py (a variant of the sqrt.py program we...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT