It seems Mathematica has a standard arithmetic system that resembles real numbers. Can we change Mathematica's original number system for arithmetic mod p so that whenever we write expressions, it sum and multiply like arithmetic mod p?
Can we change Mathematica's original number system for arithmetic mod p or other arithmetic systems?
Asked
Active
Viewed 85 times
2
-
5Define your own type and declare add and divide for these objects. You can declare a type simply be giving it a unique head. – Daniel Huber Mar 15 '21 at 08:20
-
@DanielHuber Could you write a bit more about it? I don't know much about types/heads in Mathematica and I tried to look at the documentation, didn't found about this. – Red Banana Mar 16 '21 at 04:29
-
1In addition to @BillyRubina's sample, Roman Maeder’s book „The Mathematica Programmer“, esp. Chapter 2 on „Abstract Data Types“, might be interesting for you – if you can still get your hands on a copy, that is. – user7515079 Mar 16 '21 at 17:38
1 Answers
2
Here are some very simple examples.
As a first most simple example, let us define a type, call it z5 that implements the addition group of Z/5, the integers modulo 5:
Clear[a, b, z5];
z5 /: z5[x1_] + z5[x2_] := z5[Mod[x1 + x2, 5]];
z5 /: z5[x1_] - z5[x2_] := z5[Mod[x1 - x2, 5]];
a = z5[2];
b = z5[4];
a + b
a - b
One may easily extend this to the ring Z/5 of integers modulo 5:
Clear[a, b, z5];
z5 /: z5[x1_] + z5[x2_] := z5[Mod[x1 + x2, 5]];
z5 /: z5[x1_] - z5[x2_] := z5[Mod[x1 - x2, 5]];
z5 /: z5[x1_]* z5[x2_] := z5[Mod[x1* x2, 5]];
a = z5[2];
b = z5[4];
a + b
a - b
a b
Or a bit more complicated, let us define a type that implements the ring of rational numbers:
Clear[rat, a, b];
rat /: rat[i1_, i2_] + rat [i3_, i4_] :=
rat[tmp = (i1 i4 + i3 i2)/(i2 i4); Numerator[tmp], Denominator[tmp]]
rat /: rat[i1_, i2_] - rat [i3_, i4_] :=
rat[tmp = (i1 i4 - i3 i2)/(i2 i4); Numerator[tmp], Denominator[tmp]]
rat /: rat[i1_, i2_]*rat [i3_, i4_] :=
rat[tmp = i1 i3/(i2 i4); Numerator[tmp], Denominator[tmp]]
rat /: rat[i1_, i2_]/rat [i3_, i4_] :=
rat[tmp = i1 i4/(i2 i3); Numerator[tmp], Denominator[tmp]]
a = rat[1, 2];
b = rat[2, 3];
a + b
a - b
a b
a/ b
If you want to dive into object orientation with MMA, you may read the classic:
Daniel Huber
- 51,463
- 1
- 23
- 57


