UP | HOME

Exercise 7 solutions

Table of Contents


Python

e07.py

from math import sqrt
x = float(raw_input("Enter a number x and I will compute sqrt(x):"))
niter = int(raw_input("How many iterations? "))
i = 0
xi = 10
while (i < niter):
    xi = xi - ((xi*xi)-x) / (2*xi)
    i = i + 1
print "after %d iterations, sqrt(%.5f) = %.5f" % (i, x, xi)
err = xi - sqrt(x)
print "the error is " + str(err)

MATLAB / Octave

e07.m

x = input('Enter a number x and I will compute sqrt(x):');
niter = input('How many iterations? ');
i = 0;
xi = 10;
while (i < niter)
    xi = xi - ((xi*xi)-x) / (2*xi);
    i = i + 1;
end
disp(['after ',num2str(i),' iterations, sqrt(',num2str(x),') = ',num2str(xi)]);
err = xi - sqrt(x);
disp(['the error is ',num2str(err)]);

R

e07.R

x <- as.numeric(readline("Enter a number x and I will compute sqrt(x): "))
niter <- as.integer(readline("How many iterations? "))
i <- 0
xi <- 10
while (i < niter) {
    xi <- xi - ((xi*xi)-x) / (2*xi)
    i <- i + 1
}
cat("after",i,"iterations, sqrt(",x,") = ",xi,"\n")
err <- xi - sqrt(x)
cat("the error is ", err,"\n")

C

e07.c

// compile with: gcc -o e07 e07.c

#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[]) {

  printf("Enter a number x and I will compute sqrt(x): ");
  double x;
  scanf("%lf", &x);
  printf("How many iterations? ");
  int niter;
  scanf("%d", &niter);
  int i = 0;
  double xi = 10;
  while (i < niter) {
    xi = xi - ((xi*xi)-x) / (2*xi);
    i = i + 1;
  }
  printf("after %d iterations, sqrt(%.5f) = %.5f\n", i, x, xi);
  double err = xi - sqrt(x);
  printf("the error is %.20f\n", err);

  return 0;
}

Bonus question

e07b.py

# start ipython instead of plain python, with:
# ipython --pylab
# (this loads mathy stuff and plotting stuff automagically)
# and then run the program from within iPython by typing:
# %load e07b.py
# and then hit ENTER twice

x = 612
guesses = (5,10,20,40,80)
iters = range(1,11)
for i_guess in guesses:
    errors = zeros((len(iters))) # initialize an array
    for i_iters in range(0,len(iters)):
        print "testing %d iterations with intial guess %d" % (iters[i_iters], i_guess)
        i = 0
        xi = i_guess
        while (i < iters[i_iters]):
            xi = xi - ((xi*xi)-x) / (2*xi)
            i = i + 1
        print "after %d iterations, sqrt(%.5f) = %.5f" % (i, x, xi)
        err = xi - sqrt(x)
        errors[i_iters] = err
        print "the error is " + str(err)
    plot(iters, errors, '.-')

# in the plot that results you can see that the different lines
# (corresponding to the different initial guesses) all decrease quite
# rapidly with the number of iterations and that there is some
# dependence on the initial guess

e07b.m

x = 612;
figure
hold on % set up the figure so that successive plot() commands overlay lines
guesses = [5,10,20,40,80];
iters = 1:10;
for i_guess = guesses
    errors = zeros(length(iters),1); % initialize an array
    for i_iters = 1:length(iters)
        disp(['testing ',num2str(iters(i_iters)),' iterations with intial guess ',num2str(i_guess)]);
        i = 0;
        xi = i_guess;
        while (i < i_iters)
            xi = xi - ((xi*xi)-x) / (2*xi);
            i = i + 1;
        end
        disp(['after ',num2str(i),' iterations, sqrt(',num2str(x),') = ',num2str(xi)]);
        err = xi - sqrt(x);
        errors(i_iters) = err;
        disp(['the error is ',num2str(err)]);
    end
    plot(iters, errors, '.-')
end

% in the plot that results you can see that the different lines
% (corresponding to the different initial guesses) all decrease quite
% rapidly with the number of iterations and that there is some
% dependence on the initial guess

e07b.R

x <- 612
guesses <- c(5,10,20,40,80)
iters <- 1:10
firstplot = TRUE
for (i.guess in guesses) {
    errors <- matrix(0,1,length(iters)) # initialize array of 0s
    for (i.iters in iters) {
	cat("testing ",iters[i.iters],"iterations with initial guess ", i.guess)
	i <- 0
	xi <- i.guess
	while (i < iters[i.iters]) {
	    xi <- xi - ((xi*xi)-x) / (2*xi)
	    i <- i + 1
	}
	cat("after",i,"iterations, sqrt(",x,") = ",xi,"\n")
	err <- xi - sqrt(x)
	errors[i.iters] = err
	cat("the error is ", err,"\n")
    }
    if (firstplot) {
	plot(iters, errors, type="b")
	firstplot = FALSE
    }
    else {
	lines(iters, errors, type="b")
    }
}

Paul Gribble | fall 2014
This work is licensed under a Creative Commons Attribution 4.0 International License
Creative Commons License