How can I write a code that approximates a function within a specific error?

2 views (last 30 days)
Hello. I am helping a buddy of mine test a code for one of projects. Here's a draft of what the basis of the code should look like (notes taken in class):
rootnum = input('Enter a number to take sqrt of: ');
actual = sqrt(rootnum);
guess = input('Enter an initial guess: ');
usererror = input('Enter the error: ');
error = 1000;
i = 1;
fprintf('Iteration Approximation Percent Error\n')
while (1)
guess = (guess + rootnum/guess)/2;
error = abs(guess - actual)/actual;
fprintf('%d %f %f\n',i,guess,error)
i = i + 1;
if error < usererror, break, end
end
Essentially, he needs to use this skeleton code and do the following: Create a program that allows the user to enter a value in radians and an error to approximate the cos(x) below that error. After the value is entered, the program should return the MATLAB approximation for cos(x) and a table containing the order of the polynomial used to represent cos(x), the values for the sum of the series at i=0,1,2..., and the error between the series value and the MATLAB value.
Any help?
  1 Comment
dpb
dpb on 28 Jul 2014
When he shows his work and asks a specific question over a trouble-spot, undoubtedly. Until, not so much...

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 2 Aug 2014
Looks like all he has to do is call cos() instead of sqrt() to get the "true" value. Looks like the first two lines are mostly what needs to be changed. You will also have to keep track of the guesses in the loop with an array so guess has to have an index i.
And of course that while loop is junk. Never execute a while loop without a failsafe to bail out if something goes wrong, like i > 1000000 or something, or else you can get caught in an infinite loop. Not sure why, but apparently they skip over how to write robust code in introductory classes.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

No tags entered yet.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!