Message Boards Message Boards

GROUPS:

Dealing with pairs imported as rationals

Posted 5 months ago
1001 Views
|
8 Replies
|
3 Total Likes
|

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?

8 Replies
Posted 5 months ago

From this MSE post.

Internal`RationalNoReduce[1112, 1122]
(* 1112/1122 *)

Use it in your score function.

Posted 5 months ago

I don't get it. The function score has one parameter. Your function expects two values.

Posted 5 months ago

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 *)

One way might be:

Attributes[score] = HoldAll;
score[n_] := score @@ List[Numerator[Unevaluated@n], Denominator[Unevaluated@n]]
score[1112/1122]
(*   Out:  score[1112,1122]   *)
Posted 5 months ago

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]

Posted 5 months ago

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.

Posted 5 months ago

It seems only if it is passed in an unreduced form

ClearAll@f
f[r_Rational] := r
f[Internal`RationalNoReduce[2, 4]]
(* 2/4 *)
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract