Essays/Square Root

From J Wiki
Jump to: navigation, search

Compute the square root of integer y to x decimal places.


Scaled Primitive

sqrt0=: 4 : '<.@%: y*10x^2*x'

For example:

   50 sqrt0 2
141421356237309504880168872420969807856967187537694
   80 sqrt0 2
141421356237309504880168872420969807856967187537694807317667973799073247846210703

Newton Iteration

sqrt1 is based on the fact that:

sqrt1=: 4 : '-:@(+y&%)^:(0>.>._4+2^.x) x:!.0 %:y'

For example:

   0j_10 ": y - *: 100 sqrt1 y=: 2
_2.0795900715e_127
   0j_10 ": y - *: 500 sqrt1 y=: 2
_3.6529268908e_510

   t=: 50 sqrt1 y
   t
822752278660603391920457200844167133149441322120437483433082337r581773715477596656...
   0j50 ": t
1.41421356237309504880168872420969807856967187537695



See also


Contributed by Roger Hui.