Message Boards Message Boards

0
|
4451 Views
|
8 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Dealing with pairs imported as rationals

Posted 3 years ago

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?

POSTED BY: Douglas Kubler
8 Replies
Posted 3 years ago

From this MSE post.

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

Use it in your score function.

POSTED BY: Rohit Namjoshi
Posted 3 years ago

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

POSTED BY: Douglas Kubler

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 BY: Henrik Schachner
Posted 3 years 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 *)
POSTED BY: Rohit Namjoshi
Posted 3 years ago

Yes, perfect. Works even with the explicit overloading

score[n_Rational] := 
 score @@ List[Numerator[Unevaluated@n], Denominator[Unevaluated@n]]

Thank you.

POSTED BY: Douglas Kubler

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 BY: Henrik Schachner
Posted 3 years 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 BY: Updating Name
Posted 3 years 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 *)
POSTED BY: Rohit Namjoshi
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