Arithmetic/Rational: Difference between revisions
Content added Content deleted
m (J: spell out the operations requested in the task description) |
|||
Line 1,640: | Line 1,640: | ||
=={{header|J}}== |
=={{header|J}}== |
||
Rational numbers in J may be formed from fixed precision integers by first upgrading them to arbitrary precision integers and then dividing them: |
|||
J implements rational numbers: |
|||
<lang |
<lang J> (x: 3) % (x: -4) |
||
_3r4 |
|||
⚫ | |||
3 %&x: -4 |
|||
⚫ | |||
Note that the syntax is analogous to the syntax for floating point numbers, but uses <code>r</code> to separate the numerator and denominator instead of <code>e</code> to separate the mantissa and exponent. |
|||
Thus: |
|||
<lang J> |
|||
| _3r4 NB. absolute value |
|||
3r4 |
|||
-2r5 NB. negation |
|||
_2r5 |
|||
3r4+2r5 NB. addition |
|||
23r20 |
|||
3r4-2r5 NB. subtraction |
|||
7r20 |
|||
3r4*2r5 NB. multiplication |
|||
3r10 |
|||
3r4%2r5 NB. division |
|||
15r8 |
|||
3r4 <.@% 2r5 NB. integer division |
|||
1 |
|||
3r4 (-~ <.)@% 2r5 NB. remainder |
|||
_7r8 |
|||
3r4 < 2r5 NB. less than |
|||
0 |
|||
3r4 <: 2r5 NB. less than or equal |
|||
0 |
|||
3r4 > 2r5 NB. greater than |
|||
1 |
|||
3r4 >: 2r5 NB. greater than or equal |
|||
1 |
|||
3r4 = 2r5 NB. equal |
|||
0 |
|||
3r4 ~: 2r5 NB. not equal |
|||
1</lang> |
|||
You can also coerce numbers directly to rational using x: (or to integer or floating point as appropriate using its inverse) |
|||
<lang J> x: 3%4 |
|||
3r4 |
|||
x:inv 3%4 |
|||
0.75</lang> |
|||
Increment and decrement are also included in the language, but you could just as easily add or subtract 1: |
|||
<lang J> >: 3r4 |
|||
7r4 |
|||
<: 3r4 |
|||
_1r4</lang> |
|||
J does not encourage the use of specialized mutators, but those could also be defined: |
|||
<lang j>mutadd=:adverb define |
|||
(m)=: (".m)+y |
|||
) |
|||
mutsub=:adverb define |
|||
(m)=: (".m)-y |
|||
)</lang> |
|||
Note that the name whose association is being modified in this fashion needs to be quoted (or you can use an expression to provide the name): |
|||
<lang J> n=: 3r4 |
|||
'n' mutadd 1 |
|||
7r4 |
|||
'n' mutsub 1 |
|||
3r4 |
|||
'n' mutsub 1 |
|||
_1r4</lang> |
|||
(Bare words to the immediate left of the assignment operator are implicitly quoted - but this is just syntactic sugar because that is such an overwhelmingly common case.) |
|||
That said, note that J's floating point numbers work just fine for the stated problem: |
That said, note that J's floating point numbers work just fine for the stated problem: |
||
<lang j> is_perfect_rational=: 2 = (1 + i.) +/@:%@([ #~ 0 = |) ]</lang> |
<lang j> is_perfect_rational=: 2 = (1 + i.) +/@:%@([ #~ 0 = |) ]</lang> |