Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %% Square Root of a Number
- % This code allows users to calculate the square root of a given number
- % when given an initial guess
- clc, clear
- a = input( 'Enter a positive number "a" to be square-rooted' );
- while a <= 0
- a = input( 'Enter number that is greater than 0 \n' );
- end %while
- fprintf ( 'The value of a is recorded as: %i \n', a )
- x = input( 'Enter a positive number to be the initial guess of the square root' );
- while x <= 0
- x = input( 'Enter a number that is greater than 0 \n');
- end %while
- abs_tol = 10^-5;
- xOld = x;
- while 1
- xNew = ( xOld + ( a/xOld ) )/2;
- if ( abs( xNew - xOld ) < abs_tol )
- break;
- end %if statement
- xOld = xNew;
- fprintf ( 'The current guess for the square root is %i \n', xNew);
- end %while
- fprintf( 'The actual square root of %i is %i',a,xNew)
- %{
- This code will print the estimate for the square root until it is in range
- of the absolute tolerance
- The absolute tolerance can be edited in line 20
- %}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement