## Rational Approximation

For users of dfns, both novice and expert

### Rational Approximation

Providing you have the following patch installed:

3745: Logged & Fixed (Versions: 11.0.1) 2008-09-08
Tolerant GCD and LCM for non-integers have been improved.

here's function, which uses GCD to find the smallest pair, whose quotient is tolerably equal to the argument:

Code: Select all
`    rational←{⎕ml←0 ⋄ ↑⍵ 1÷⊂1∨⍵}`

The shape of the result is the same as that of the (possibly nested) argument but with an additional leading length-2 axis.

Code: Select all
`    rational 12.3 0.456 7.89123  57 789 10 125 100     rational ○1      ⍝ rational within ⎕CT of pi.5419351 1725033`

JohnS|Dyalog

### Re: Rational Approximation

We could supply comparison tolerance as an optional left argument to rational thus:

Code: Select all
`    rational←{⎕ML←0      ⍝ rational approximation to real ⍵.        ⍺←⎕CT ⋄ ⎕CT←⍺    ⍝ default tolerance.                       ↑⍵ 1÷⊂1∨⍵        ⍝ ⍵≡÷⌿∇⍵                               }                                                          rational ○1          ⍝ default tolerance.5419351 1725033    (16*¯8) rational ○1  ⍝ coarse tolerance.103993 33102    0 rational ○1        ⍝ zero-tolerance.245850922 78256779`

NB: the final example might seem strange in that, with zero tolerance, pi is certainly not equal to any rational number. However ○1 is not exactly pi; it is the best IEEE double floating approximation to pi and all IEEE floating point numbers are rational (Yeah?).
JohnS|Dyalog