四元组类,定义了四元组类的各种方法


本文内容

本文定义了四元组类以及它的一些方法


一、定义

提示:这里可以添加本文要记录的大概内容:
四元组的定义:
𝑞=𝑎+𝑏𝑖+𝑐𝑗+𝑑𝑘⟺𝑞=(𝑎,𝑏,𝑐,𝑑) ∈ ℝ4
其中,q是一个tuple类型的

def quaternion_test(q): 
    
    ## INPUT YOUR CODE BELOW THIS LINE ## 
    #If q is not a tuple
    if not isinstance(q,tuple):
        raise TypeError('Input is not tuple.')
    #If len(q) is not 4
    if len(q)!=4:
        raise ValueError('Input is not length 4.')
    #If one of the elements of q is not either a float or int,
    #Judge the type of each element in a loop
    if False in[isinstance(i,int) or isinstance(i,float)  for i in q]:
        raise TypeError('Element not a real number.')
    return None

提示:以下是本篇文章正文内容,下面案例可供参考

二、基本操作

1.获取四元组的实数、虚数部分

def real(q):
    
     ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    #return the real part
    return q[0]
   
def imag(q):
    
     ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    #return the imag part
    return q[1] 
    
def jmag(q):
    
     ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    #return the imag part
    return q[2]  
    
def kmag(q):
    
     ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    #return the imag part
    return q[3]
    

2.str化

def string(q):
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    a=q[0]
    #Add '+' to the coefficients in the complex part
    b='+'+str(q[1]) if q[1]>=0 else q[1]
    c='+'+str(q[2]) if q[2]>=0 else q[2]
    d='+'+str(q[3]) if q[3]>=0 else q[3]
    cpl=str(b)+'i'+str(c)+'j'+str(d)+'k'
    if a==0:
        string=cpl[1:] if cpl[0]=='+' else cpl
    else:
        string=str(a)+cpl
    return '('+string+')'

3.相加

def add(q,r):
    
    ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    quaternion_test(r)
    
    return (q[0]+r[0],q[1]+r[1],q[2]+r[2],q[3]+r[3])

4.取反

def negative(q):
    
    ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    #Tuple to List,Beacause the tuple cannot be changed.
    q=list(q)
    #alter the value to -value for every element
    for index,value in enumerate(q):
        q[index]=-value
    return tuple(q)

5.相减

def subtract(q,r):
    
    ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    quaternion_test(r)
    
    return (q[0]-r[0],q[1]-r[1],q[2]-r[2],q[3]-r[3])

6.相乘

def multiply(q,r):
    
    ## INPUT YOUR CODE BELOW THIS LINE ##
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    quaternion_test(r)
    #scalar,i,j,k part multiply each other
    res=[]
    for m in range(4):
        line=[]
        for n in range(4):
            line.append(r[n]*q[m])
        res.append(line)
    a=res[0][0]-res[1][1]-res[2][2]-res[3][3]
    b=res[0][1]+res[1][0]+res[2][3]-res[3][2]
    c=res[0][2]+res[2][0]-res[1][3]+res[3][1]
    d=res[0][3]+res[3][0]+res[1][2]-res[2][1]
    return (a,b,c,d)

6.共轭复数

def conjugate(q):
    
    ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    #Tuple to List,Beacause the tuple cannot be changed.
    q=list(q)
    #alter the value to -value for every element
    for index in range(len(q)-1):
        q[index+1]=-q[index+1]
    return tuple(q)

7.取绝对值

def absolute_value(q):
    
    ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    #Call the function to find the  conjugate of q,and multiply it and q. 
    #Fisrtly,find the q*
    q_conjugate=conjugate(q)
    #Secondly,q  x q*
    product=multiply(q,conjugate(q))
    #Finally,take the sum of each element, and  take the square root of the sum
    return sum(product)**0.5

8.求逆

def inverse(q):  
    
    ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    #A list for storing the result
    result=[]
    #Fisrtly,find the conjugate q*
    q_conjugate=conjugate(q)
    #And then find the |q|*|q|
    q_square=absolute_value(q)**2
    #In the last,divide every element of the conjugate by q_square
    for i in q_conjugate:
        result.append(i/q_square)
    return tuple(result)

9.除法

def divide(q,r):
    
    ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    quaternion_test(r)
    #Find r-1,the inverse of r
    r_inverse=inverse(r)
    #Multiply q and r-1
    result=multiply(q,r_inverse)
    
    return result

10.指数运算

def power(q,n):
    
    ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Use function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    #Judge the type of n
    if not isinstance(n,int):
        raise TypeError('Input is not int.')
    #If n=0,return (1,0,0,0)
    if n==0:
        return (1,0,0,0)
    #if n >0, call the function 'multiply' to calculate the value
    if n>0:
        result=q
        for i in range(abs(n)-1):
            result=multiply(result,q)
        return result
    #if n<0,turn the q to inverse(q)
    else:
        result=inverse(q)
        for i in range(abs(n)-1):
            result=multiply(inverse(q),result)
        return result

11.complex_pair

def complex_pair(q):
    
     ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Call function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    
    part1=complex(q[0],q[1])
    part2=complex(q[2],q[3])

    return tuple((part1,part2))

11.matrix矩阵

import numpy as np

def matrix(q):
    
     ## INPUT YOUR CODE BELOW THIS LINE ## 
    #Call function quaternion_test to judge the validity of quaternion
    quaternion_test(q)
    #Write the complex number to a two-dimensional list
    matrix=[[complex(q[0],q[1]),complex(q[2],q[3])],[-complex(q[2],q[3]).conjugate(),complex(q[0],q[1]).conjugate()]]
    
    return np.array(matrix)

三、类

1.四元组类以及方法

### TEST FUNCTION: test_quaternion
## DO NOT REMOVE ANYTHING IN THIS CELL ##

import numpy as np

class quaternion():
    
    def __init__(self,a=0,b=0,c=0,d=0):
        if a.imag!=0 or b.imag!=0:
            d=b.imag
            c=b.real
            b=a.imag
            a=a.real
            
        self.___q = (a,b,c,d)
        
        ## YOU MIGHT ADD THINGS TO __init__ ##
        self._a   = a
        self._b   = b
        self._c   = c
        self._d   = d
    
    
    
    ## HERE ARE TWO HELPFUL FUNCTION TO GET STARTED ##
    
    # self[item]
    def __getitem__(self,item):
        return self.___q[(item)]
    
    @classmethod
    def unit(self,i):
        return quaternion(*(i*(0,)+(1,)+(3-i)*(0,)))
    
    
    ## PUT YOUR CODE BELOW THIS LINE ##
    
    # self.real
    @property
    def real(self):
        return self._a
    
    # self.imag
    @property
    def imag(self):
        return self._b
    
    # self.jmag
    @property
    def jmag(self):
        return self._c
    
    # self.kmag
    @property
    def kmag(self):
        return self._d
    
    # self.scalar
    @property
    def scalar(self):
        return self._a
    
    # self.vector
    @property
    def vector(self):
        return (self._b,self._c,self._d)
    
    # self.complex_pair
    @property
    def complex_pair(self):
        return (complex(self._a,self._b),complex(self._c,self._d))
    
    # self.matrix
    @property
    def matrix(self):
        matrix=[[complex(self._a,self._b),complex(self._c,self._d)],[-complex(self._c,self._d).conjugate(),complex(self._a,self._b).conjugate()]]
        return np.array(matrix)
    
    # str(self)
    def __str__(self):
        b='+'+str(self._b) if self._b>=0 else self._b
        c='+'+str(self._c) if self._c>=0 else self._c
        d='+'+str(self._d) if self._d>=0 else self._d
        cpl=str(b)+'i'+str(c)+'j'+str(d)+'k'
        string=str(self._a)+cpl
        return '('+string+')'
    
    # self
    def __repr__(self):
        return str(self)
    
    # self + other
    def __add__(self,other):
        if isinstance(other,int) or isinstance(other,float) or isinstance(other,complex):
            other=quaternion(other.real,other.imag,0,0)
        return quaternion(self._a+other._a,self._b+other._b,self._c+other._c,self._d+other._d)
    
    # +self
    def __pos__(self):
        return self
    
    # -self
    def __neg__(self):
        return quaternion(-self._a,-self._b,-self._c,-self._d)
    
    # self.conjugate()
    def conjugate(self):
        return quaternion(self._a,-self._b,-self._c,-self._d)
    
    # self - other
    def __sub__(self,other):
        #if it is a object
        if isinstance(other,int) or isinstance(other,float) or isinstance(other,complex):
            other=quaternion(other.real,other.imag,0,0)
        return quaternion(self._a-other._a,self._b-other._b,self._c-other._c,self._d-other._d)
    
    # self*other
    def __mul__(self,other):
        if isinstance(other,int) or isinstance(other,float) or isinstance(other,complex):
            other=quaternion(other.real,other.imag,0,0)
        q,r=self.___q,other.___q
        part1=[q[0]*i for i in r[1:]]
        part2=[r[0]*i for i in q[1:]]
        line=[]
        #i,j,k part multiply each other
        for _q in q[1:]:
            for _r in r[1:]:
                line.append(_q*_r)
        a=q[0]*r[0]-line[0]-line[4]-line[8]
        b=part1[0]+part2[0]+line[5]-line[7]
        c=part1[1]+part2[1]-line[2]+line[6]
        d=part1[2]+part2[2]+line[1]-line[3]
        return quaternion(a,b,c,d)
    
    # self._inverse()
    def _inverse(self):
        result=[]
        q_conjugate=self.conjugate().___q
        q_square=abs(self)**2
        for i in q_conjugate:
            result.append(i/q_square)
        return quaternion(*result)
    
    # self**n
    def __pow__(self,n):
        if n==0:
            return (1,0,0,0)
        if n>0:
            result=self.___q
            for i in range(n-1):
                result=quaternion(*result)*self
            return result
        else:
            result=self._inverse()
            for i in range(-n-1):
                result=quaternion(*result) * quaternion(*self._inverse())
            return result
    
    # abs(self)
    def __abs__(self):
        other=quaternion(*self.conjugate())
        product=self*other
        return sum(product)**0.5

    
    # self/other
    def __truediv__(self,other):
        if isinstance(other,int) or isinstance(other,float) or isinstance(other,complex):
            other=quaternion(other.real,other.imag,0,0)
        #Multiply q and r-1
        result=self*quaternion(*other._inverse())
    
        return quaternion(*result)

    
    # self == other
    def __eq__(self,other):
        if isinstance(other,int) or isinstance(other,float) or isinstance(other,complex):
            other=quaternion(other.real,other.imag,0,0)
        return str(self)==str(other)
    
    # other + self
    def __radd__(self,other):
        if isinstance(other,int) or isinstance(other,float) or isinstance(other,complex):
            other=quaternion(other.real,other.imag,0,0)
        return quaternion(self._a+other._a,self._b+other._b,self._c+other._c,self._d+other._d) 
    
    # other - self
    def __rsub__(self,other):
        #if it is a object
        if isinstance(other,int) or isinstance(other,float) or isinstance(other,complex):
            other=quaternion(other.real,other.imag,0,0)
        return quaternion(-self._a+other._a,-self._b+other._b,-self._c+other._c,-self._d+other._d)

    
    # other*self
    def __rmul__(self,other):
        if isinstance(other,int) or isinstance(other,float) or isinstance(other,complex):
            other=quaternion(other.real,other.imag,0,0)
        r,q=self.___q,other.___q
        part1=[q[0]*i for i in r[1:]]
        part2=[r[0]*i for i in q[1:]]
        line=[]
        #i,j,k part multiply each other
        for _q in q[1:]:
            for _r in r[1:]:
                line.append(_q*_r)
        a=q[0]*r[0]-line[0]-line[4]-line[8]
        b=part1[0]+part2[0]+line[5]-line[7]
        c=part1[1]+part2[1]-line[2]+line[6]
        d=part1[2]+part2[2]+line[1]-line[3]
        return quaternion(a,b,c,d)

    # other/self
    def __rtruediv__(self,other):
        if isinstance(other,int) or isinstance(other,float) or isinstance(other,complex):
            other=quaternion(other.real,other.imag,0,0)
        #Multiply other and self -1
        result=other*quaternion(*self._inverse())
        return quaternion(*result)
    
    # other == self
    def __req__(self,other):
        if isinstance(other,int) or isinstance(other,float) or isinstance(other,complex):
            other=quaternion(other.real,other.imag,0,0)
        return str(self)==str(other)

2.The Octonians

### TEST FUNCTION: test_octonion
## DO NOT REMOVE ANYTHING IN THIS CELL ##

class octonion():
    
    def __init__(self,a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0):
        v=[]
        if isinstance(a,quaternion) or isinstance(b,quaternion) or isinstance(a,complex) or isinstance(b,complex):
            if isinstance(a,quaternion):
                v.extend([a._a,a._b,a._c,a._d])
            else:
                v.extend([a.real,a.imag,0,0])
            if isinstance(b,quaternion):
                v.extend([b._a,b._b,b._c,b._d])
            else:
                v.extend([b.real,b.imag,0,0])
            a,b,c,d,e,f,g,h=v  
        self.___o = (a,b,c,d,e,f,g,h)
        
        ## YOU MIGHT ADD THINGS TO __init__ ##
        self._a=a
        self._b=b
        self._c=c
        self._d=d
        self._e=e
        self._f=f
        self._g=g
        self._h=h
        self.q=quaternion(a,b,c,d)
        self.r=quaternion(e,f,g,h)
    
    
    ## HERE ARE TWO HELPFUL FUNCTION TO GET STARTED ##
    
    # self[item]
    def __getitem__(self,item):
        return self.___o[(item)]
    
    @classmethod
    def unit(self,i):
        return octonion(*(i*(0,)+(1,)+(7-i)*(0,)))
    
    
    ## PUT YOUR CODE BELOW THIS LINE ##
    
    @property
    def quaternion_pair(self):
        return ((self.q),(self.r))
        
    def __str__(self):
        #There is ambiguity here
        #According to task one,this one is right
        #return '({},{})'.format((self.q),(self.r))
        
        #According the task2 topic, this is right
        return str(self.___o)

    
    def __repr__(self):
        return str(self)
    

    def __add__(self,other):
        return octonion(self._a+other._a,self._b+other._b,self._c+other._c,self._d+other._d,self._e+other._e,self._f+other._f,self._g+other._g,self._h+other._h)

        
    def __neg__(self):
        return octonion(-self._a,-self._b,-self._c,-self._d,-self._e,-self._f,-self._g,-self._h)
    
    def __sub__(self,other):
        return octonion(self._a-other._a,self._b-other._b,self._c-other._c,self._d-other._d,self._e-other._e,self._f-other._f,self._g-other._g,self._h-other._h)
    
    def conjugate(self):
        return octonion(self.q.conjugate(),-self.r)
    
    def __mul__(self,other):
        q1=self.q
        r1=self.r
        q2=self.q
        r2=self.r
        return octonion(q1*q2-r2.conjugate()*r1,r2*q1+r1*q2.conjugate())
    
    def __pow__(self,n):
        return octonion(self.q**n,self.r**n)
    
    def __abs__(self):
        q=self.q
        r=self.r
        return abs(q)**2+abs(r)**2

    def inverse(self):
        o2=abs(self)
        q=quaternion(*[i/o2 for i in self.conjugate().q])
        r=quaternion(*[i/o2 for i in self.conjugate().r])
        return octonion(q,r)
    
    def _inverse(self):
        o2=abs(self)
        q=quaternion(*[i/o2 for i in self.conjugate().q])
        r=quaternion(*[i/o2 for i in self.conjugate().r])
        return octonion(q,r) 
    
    def __truediv__(self,other):
        result=self*octonion(*other._inverse())
        return octonion(*result)
    
    def __eq__(self,other):
        return str(self)==str(other)

    def __radd__(self,other):
        return octonion(self._a+other._a,self._b+other._b,self._c+other._c,self._d+other._d,self._e+other._e,self._f+other._f,self._g+other._g,self._h+other._h) 
    
    def __rsub__(self,other):
        return octonion(-self._a+other._a,-self._b+other._b,-self._c+other._c,-self._d+other._d,-self._e+other._e,-self._f+other._f,-self._g+other._g,-self._h+other._h) 
    
    def __rmul__(self,other):
        q2=self.q
        r2=self.r
        q1=self.q
        r1=self.r
        return octonion(q1*q2-r2.conjugate()*r1,r2*q1+r1*q2.conjugate())
    
    def __rtruediv__(self,other):
        result=other*octonion(*self._inverse())
        return octonion(*result)
    
    def __req__(self,other):
        return str(self)==str(other)
    

四、 总结

本文对四元组的基本操作进行了介绍,实现了四元组类以及八元组类。有问题可以关注知乎Durling,talk to me.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值