codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
// Compare babylonian and newton raphson #include <stdio.h> int iter = 0; double babylonian_sqrt(double arg) { double eps = 1E-16; double rt = arg / 4.0; double sq = rt * rt; while( (arg - sq > eps) || (sq - arg > eps) ) { rt += arg / rt; rt /= 2; sq = rt * rt; ++iter; } return rt; } double nr_sqrt(double arg) { double eps = 1E-16; double rt = arg / 4.0; double sq = rt * rt; while( (arg - sq > eps) || (sq - arg > eps) ) { double fx = sq - arg; double dx = 2 * rt; rt -= fx / dx; sq = rt * rt; ++iter; } return rt; } int main() { const double num = 63.; iter = 0; const double baby = babylonian_sqrt(num); printf( "Sqrt(%g) by Ancient Baylonian (After %03d iteration) = %.20g\n" , num , iter , baby); iter = 0; const double nr = nr_sqrt(num); printf( "Sqrt(%g) by Newton - Raphson (After %03d iteration) = %.20g\n" , num , iter , nr); return 0; }
Private
[
?
]
Run code
Submit