Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force Mathematica to show a rational with the denominator I specified?

I want to write a function to force Mathematica to show a rational number in a denominator I specified. For example, the rational 2/3 with the specified denominator 6 should become 4/6.

I tried using HoldForm[] or Unevaluated[], but with no success.

In[1]:= setDenominator[x_, d_] := Unevaluated[Rational[x*d, d]];

In[2]:= setDenominator[2/3, 6]

        2
Out[2]= -
        3
like image 828
Qiang Li Avatar asked Apr 08 '11 19:04

Qiang Li


3 Answers

You can use a FractionBox with DisplayForm:

setDenominator[x_, d_] := DisplayForm[FractionBox[x*d, d]]
like image 119
sakra Avatar answered Oct 29 '22 06:10

sakra


HoldForm works but you have to be sneaky to get the numerical value of x*d in there

setDenominator[x_, d_] := HoldForm@Rational[foo, d] /. foo -> x*d

This can be improved by adding some checks for the suitability of d.

like image 23
Timo Avatar answered Oct 29 '22 08:10

Timo


Here's a variation on sakra's idea that allows for addition and multiplication...

Format[setDenominator[x_, d_]] := DisplayForm@FractionBox[x*d, d]
setDenominator /: Plus[left___, setDenominator[x1_, d1_], right___] := left + x1 + right;
setDenominator /: Times[left___, setDenominator[x1_, d1_], right___] :=left*x1*right;

Trying it out:

a = setDenominator[3/5, 10];
Print[a, " + ", 2/3, " = " , a + 2/3]
Print[a, " + ", 2/3, " = " , setDenominator[a + 2/3, 30]]
Print[a, " × ", 2/3, " = " , a * 2/3]
Print[a, " × ", 2/3, " = " , setDenominator[a * 2/3, 30]]
Print[a, " ÷ ", 2/3, " = " , a /( 2/3)]

addition, multiplication, division

like image 38
DavidC Avatar answered Oct 29 '22 08:10

DavidC