0

I would like to calculate the multiplication of quaternion z4=[7,4,-2,5] with its inverse quaternion. I run my code smoothly, but this program execution result of z4*Inv(z4)=([[0.9999999999999999, 0.0, -2.7755575615628914e-17, 0.0]) is quite different from manual calculation and other online quaternion calculator=([1,0,0,0]). Is somewhere wrong in the code? I don't know how to solve the problem.

Here is the code of my program:

class Quaternion:
    def __init__(q, value):
        if type(value)!=list or len(value)!=4:
           print('Err: It must be in a list of 4 values')
        else:
            q.value=value
def Mul(q,q2):
    a=q.value[0]*q2.value[0]-q.value[1]*q2.value[1]-q.value[2]*q2.value[2]-q.value[3]*q2.value[3]
    b=q.value[0]*q2.value[1]+q.value[1]*q2.value[0]+q.value[2]*q2.value[3]-q.value[3]*q2.value[2]
    c=q.value[0]*q2.value[2]-q.value[1]*q2.value[3]+q.value[2]*q2.value[0]+q.value[3]*q2.value[1]
    d=q.value[0]*q2.value[3]+q.value[1]*q2.value[2]-q.value[2]*q2.value[1]+q.value[3]*q2.value[0]



    return Quaternion([a,b,c,d])
     
def inv(q):
  tmp=0
  for item in q.value:
      tmp+=item**2
  return (1/tmp) 



def Inv(q):

   
   return Quaternion([Quaternion.inv(q)*q.value[0],Quaternion.inv(q)*-q.value[1],Quaternion.inv(q)*-q.value[2],Quaternion.inv(q)*-q.value[3]])


            
z4= Quaternion([7,4,-2,5])
print(Quaternion.Mul(z4,Quaternion.Inv(z4)).value)

and the output result is IN[39]: print(Quaternion.Mul(z4,Quaternion.Inv(z4)).value) [0.9999999999999999, 0.0, -2.7755575615628914e-17, 0.0]

Evelyn
  • 9
  • 3
  • *is quite different from manual calculation* -> There is a small difference due to the precision of float32 values, but the results are pretty close. – Lescurel Nov 10 '20 at 15:04
  • 1
    https://www.geeksforgeeks.org/floating-point-error-in-python/ – Alex Reynolds Nov 10 '20 at 15:05
  • Does this answer your question? [How to avoid floating point errors?](https://stackoverflow.com/questions/19473770/how-to-avoid-floating-point-errors) – Alex Reynolds Nov 10 '20 at 15:06
  • so actually the value of the third one is 0 , but the python program calculated that it is -2.7755575615628914e-17, is this is a floating point error? – Evelyn Nov 10 '20 at 15:16
  • This is normal floating point arithmetic behavior. This can be mitigated to some extent by using larger formats (single instead of half, double instead of single, etc.), but these effects will always be present with any floating point format you use. – James Tursa Nov 10 '20 at 23:25

0 Answers0