Essays/Large Exponent Real Arithmetic

From J Wiki
Jump to: navigation, search

Two 64-bit floating point numbers are used to represent the base-10 mantissa and exponent of a real number, encoded as a single complex atom. Therefore, in this representation 3.124j2 is the number 312.4 and _3.44j0 is the number _3.44 .

Operations

plus=: 4 : 0 " 0
 'x xe'=. +. x
 'y ye'=. +. y
 e=. xe>.ye
 z=. (x*10^xe-e)+y*10^ye-e
 (0~:z) * (z%10^k) j. e+k=. <.10^.|z
)

minus=: _1 1&*"1&.+. : (plus $:) " 0

times=: 4 : 0 " 0
 'x xe'=. +. x
 'y ye'=. +. y
 z=. x*y
 (0~:z) * (z%10^k) j. xe+ye+k=. <.10^.|z
)

div=: 4 : 0 " 0
 'x xe'=. +. x
 'y ye'=. +. y
 if. 0=x do. 0 return. end.
 if. 0=y do. (*x){0 _ __ return. end.
 z=. x%y
 (z%10^k) j. (xe-ye)+k=. <.10^.|z
)

pow=: 4 : 0 " 0
 'x xe'=. +. x
 'y ye'=. +. y
 if. 0=x do. (*y){1 0 _ return. end.
 n=. y*10^ye
 assert. (0<x)+.n=<.n  NB. complex number
 ((_1^(0>x)*.2|n) * 10^z-e) j. e=. <.z=. n*xe+10^.|x
)

log=: 10&$: : (4 : 0) " 0
 'x xe'=. +. x
 'y ye'=. +. y
 assert. (0<x)*.0<y
 (ye+10^.y) div (xe+10^.x)
)

Examples

   3j4 plus 5j6
5.03j6
   3j4 times 5j6
1.5j11
   minus~ 3j4
0
   3j4 div 5j6
6j_3
   3j4 pow 12
5.31441j53
   3j4 pow 1 12 123456
3j4 5.31441j53 3.03126j552727

   0 pow _5 0 5
_ 1 0

   div/~ i: 3
          1   1.5  3 __ _3  _1.5          _1
 6.66667j_1     1  2 __ _2    _1 _6.66667j_1
 3.33333j_1  5j_1  1 __ _1 _5j_1 _3.33333j_1
          0     0  0  0  0     0           0
_3.33333j_1 _5j_1 _1  _  1  5j_1  3.33333j_1
_6.66667j_1    _1 _2  _  2     1  6.66667j_1
         _1  _1.5 _3  _  3   1.5           1

An Application

The n-th Fibonacci number can be computed as <. 0.5 + (%:5) %~ phi^n . Thus:

   phi=: -: 1+%:5
   (%:5) div~ phi pow 2749
1.43727j574

   fmt=: ":!.16

   fmt (%:5) div~ phi pow 2749
1.437268955338741j574

f7 from the Fibonacci numbers page computes the result exactly:

f7=: 3 : 0
 mp=. +/ .*
 {.{: mp/ mp~^:(I.|.#:y) 2 2$0 1 1 1x
)

   f7 2749
143726895533879176618296456715643341443476345064489177 ...
   0j_20 ": f7 2749
1.43726895533879176618e574

Fib 2749 is pandigital in its leading 9 digits.



Contributed by Roger Hui.