I wanted to know how computers calculate basic functions like Sqrt
so first I checked how humans do it I found that they use something called "Newton's method" that is basically a iterative method to find the root of a number.
that can be efficiently reproduced in Mathematica as:
SqRoot[x_, assump_, precision_] := N[Nest[(# + x/#)/2 &, assump, 21], precision]
Timing
it for 2 gives:
In:= Timing[SqRoot[2, 1, 123]]
Out:= {1.75, 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492}
1.75 Seconds
While using same precision with Sqrt
gives:
In:=Timing[N[Sqrt[2], 123]]
Out:= {1.6237*10^-15,1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492}
1.6237*10^-15 Seconds
Meaning Mathematica uses an entirely different operation to calculate the root of a number
Like this there are tons of elementary functions like Factorial
Abs
Solve
Sin
Cos
which result in similar fast results as compared to slower human results using slower loops and iterative methods.
Where can we find a compendium of all the back code that supports these functions and makes them faster than actual procedure.
P.S. This is related only to Mathematica based functions (not theoreticalcs.SE)
Timing
does not mean thatMathematica
uses an entirely different operation ! Functions likeSqrt
are written in a compiled language (C
),Mathematica
is basically interpreted. You can look how it is evaluated e.g.Trace[N[Nest[(2 + x/2)/2, 1, 21], 123] ]
$\endgroup$N[]
is outside as opposed to being within theNest[]
, and the rational numbers that get generated become more unwieldy. $\endgroup$FixedPoint[(# + 2/#)/2 &, N[1, 123]] // AbsoluteTiming
$\endgroup$