python advanced five (custom class) [5-4] math python

python in math

The basic data types provided int Python, float can be made of four integer and floating point arithmetic operation and the like, and exponentiation.

However, not limited to the four operations int and float, which may also be a rational number, matrix and the like.

To represent rational numbers , you can use a Rational class to represent:

1 class Rational(object):
2     def __init__(self, p, q):
3         self.p = p
4         self.q = q

p, q are integers, it denotes a rational number P / Q .

If you want Rational conduct the + operator, you need to properly implement __add__ :

1 class Rational(object):
2     def __init__(self, p, q):
3         self.p = p
4         self.q = q
5     def __add__(self, r):
6         return Rational(self.p * r.q + self.q * r.p, self.q * r.q)
7     def __str__(self):
8         return '%s/%s' % (self.p, self.q)
9     __repr__ = __str__

You can now try the rational addition:

>>> r1 = Rational(1, 3)
>>> r2 = Rational(1, 2)
>>> print r1 + r2
5/6

task

Although you can do addition Rational class, but can not do subtraction, division and power, continue to improve Rational class that implements the four operations.

Tip:
subtraction: __ sub__
multiplication: __ mul__
division: __ div__

. 1  DEF GCD (a, b): 
# set for the next two numbers a, b (a> b) , the step of seeking the greatest common divisor of a and b (a, b), such as #: with a by b, to give a ÷ b = q ..... r1 (0≤r1) . When r1 = 0, then (A, b) = b;
. # If # r1 ≠ 0, then b is divided by r1, to give b ÷ r1 = q ....... r2 ( 0≤r2) if r2 = 0, then (a, # b) = r1 , if 0 ≠ R2,
# continue with divided r1 r2, and so on until divisible so far. After one of its most # is the divisor (a, b) the remainder of the dividend.
2 . 3 # example: a = 25, b = 15 , a% b = 10, b% 10 = 5,10% 5 = 0, one of the last I # dividend divisor is the greatest common divisor is 5,5 . . 4 IF B == 0: . 5 return A . 6 return GCD (B, A% B) . 7 . 8 class the Rational (Object): . 9 DEF the __init__ (Self, P, Q): 10 self.p = P . 11 self.q = q 12 def __add__(self, r): 13 return Rational(self.p * r.q + self.q * r.p, self.q * r.q) 14 def __sub__(self, r): 15 return Rational(self.p * r.q - self.q * r.p, self.q * r.q) 16 def __mul__(self, r): 17 return Rational(self.p * r.p, self.q * r.q) 18 def __div__(self, r): 19 return Rational(self.p * r.q, self.q * r.p) 20 def __str__(self): 21 GCD = G (self.p, self.q) # G is the greatest common divisor of 22 is return ' % S / S% ' % (self.p / G, self.q / G) 23 is __repr__ = __str__ 24 25 R1 = the Rational (. 1, 2 ) 26 is R2 = the Rational (. 1,. 4 ) 27 Print R1 + R2 28 Print R1 - R2 29 Print R1 * R2 30 Print R1 / R2

 

 

Guess you like

Origin www.cnblogs.com/ucasljq/p/11626750.html