How to make Mathematica show rationality with the indicated denominator?

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

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

 In[1]:= setDenominator[x_, d_] := Unevaluated[Rational[x*d, d]]; In[2]:= setDenominator[2/3, 6] 2 Out[2]= - 3 
+6
source share
4 answers

You can use FractionBox with DisplayForm :

 setDenominator[x_, d_] := DisplayForm[FractionBox[x*d, d]] 
+6
source

HoldForm works, but you have to be sneaky to get a numerical value x*d there

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

This can be improved by adding some validation d .

+4
source

Here is a variation of the idea of ​​sacra, which allows you to add and multiply ...

 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; 

Attempt:

 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

+4
source

An alternative for the sakra example is to store the value in a string:

 setDenominator[x_, d_] := ToString[xd] <> "/" <> ToString[d]; 
0
source

Source: https://habr.com/ru/post/885531/


All Articles