mysqrt.cxx 483 Bytes
Newer Older
Ken Martin's avatar
Ken Martin committed
1
#include "MathFunctions.h"
Betsy McPhail's avatar
Betsy McPhail committed
2
#include <iostream>
Ken Martin's avatar
Ken Martin committed
3 4 5 6

// a hack square root calculation using simple operations
double mysqrt(double x)
{
7
  if (x <= 0) {
Ken Martin's avatar
Ken Martin committed
8
    return 0;
9
  }
10

Betsy McPhail's avatar
Betsy McPhail committed
11
  double result = x;
Ken Martin's avatar
Ken Martin committed
12 13

  // do ten iterations
Betsy McPhail's avatar
Betsy McPhail committed
14
  for (int i = 0; i < 10; ++i) {
15
    if (result <= 0) {
Ken Martin's avatar
Ken Martin committed
16 17
      result = 0.1;
    }
Betsy McPhail's avatar
Betsy McPhail committed
18
    double delta = x - (result * result);
19
    result = result + 0.5 * delta / result;
Betsy McPhail's avatar
Betsy McPhail committed
20
    std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
21
  }
Ken Martin's avatar
Ken Martin committed
22 23
  return result;
}