dckubler
(Douglas Kubler)
June 1, 2021, 6:11pm
1
I coded processing for race data where the position of a competitor is published as n/m.
That led to passing the data as published like this -
score[n_Rational] := score[Numerator[n], Denominator[n]] ;
That worked (for a non-linear scoring) until
score[1112/1122]
produced the actual value for
score[556, 561]
Mathematica reduced the rational to lowest terms. Sure, it’s the numeric equivalent but not the values I wanted. How do I get to the original rational?
From this MSE post.
Internal`RationalNoReduce[1112, 1122]
(* 1112/1122 *)
Use it in your score function.
dckubler
(Douglas Kubler)
June 1, 2021, 7:59pm
3
I don’t get it. The function score has one parameter. Your function expects two values.
One way might be:
Attributes[score] = HoldAll;
score[n_] := score @@ List[Numerator[Unevaluated@n], Denominator[Unevaluated@n]]
score[1112/1122]
(* Out: score[1112,1122] *)
It has to be two values to prevent evaluation. You would have to do something like
ClearAll@score
Attributes[score] = HoldFirst;
score[r_] := Hold@r /. Times[n_, Power[d_, -1]] :> Internal`RationalNoReduce[n, d] //
ReleaseHold
score[1112/1122]
(* 1112/1122 *)
dckubler
(Douglas Kubler)
June 1, 2021, 10:08pm
6
Yes, perfect. Works even with the explicit overloading
score[n_Rational] :=
score @@ List[Numerator[Unevaluated@n], Denominator[Unevaluated@n]]
Thank you.
Works even with the explicit overloading
No, I am afraid it does not! With
score[n_Rational] := ...
it just echoes the input.
You probably should do a Clear[score]
You’re right, the the my n_Rational definition is ignored and defaults to your global.
It only looks like it works as intended by passing tests.
I’m back to wondering if a parameter can ever be (1) a Rational type and (2) unreduced.
It seems only if it is passed in an unreduced form
ClearAll@f
f[r_Rational] := r
f[Internal`RationalNoReduce[2, 4]]
(* 2/4 *)