티스토리 뷰

python

단위 사원수의 곱 - 파이썬 코드

게으른 the lazy 2020. 7. 4. 16:01

출처: https://en.wikipedia.org/wiki/Quaternion

 

두 가지 방법으로 짜보았습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# product of two unit quaternions
# without using if-else
 
def calProdUnitQuat(arg1, arg2):
    # input string -> Boolean    
    q1 = [arg1=='1'+ [arg1==for s in 'ijk']
    q2 = [arg2=='1'+ [arg2==for s in 'ijk']
    q3 = [0]*4
    # https://personal.utdallas.edu/~sxb027100/dock/quaternion.html
    q3[0= q1[0]*q2[0- q1[1]*q2[1- q1[2]*q2[2- q1[3]*q2[3]
    q3[1= q1[0]*q2[1+ q1[1]*q2[0+ q1[2]*q2[3- q1[3]*q2[2]
    q3[2= q1[0]*q2[2- q1[1]*q2[3+ q1[2]*q2[0+ q1[3]*q2[1]
    q3[3= q1[0]*q2[3+ q1[1]*q2[2- q1[2]*q2[1+ q1[3]*q2[0]
    sign = ('' if any(i>0 for i in q3) else '-')
    q3 = [abs(i) for i in q3]
    q3 = ''.join([n*for n,s in zip(q3,'1ijk')])
    return sign + ''.join(q3)
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# product of two unit quaternions
# throwing a party of if-else
 
def calProdUnitQuat2(arg1, arg2):
    if arg1=='1':
        return arg2
    if arg2=='1':
        return arg1
    if arg1=='i':
        if arg2=='i':
            return '-1'
        if arg2=='j':
            return 'k'
        if arg2=='k':
            return '-j'
    if arg1=='j':
        if arg2=='i':
            return '-k'
        if arg2=='j':
            return '-1'
        if arg2=='k':
            return 'i'
    if arg1=='k':
        if arg2=='i':
            return 'j'
        if arg2=='j':
            return '-i'
        if arg2=='k':
            return '-1'
cs

 

속도를 비교해보았습니다. 두번째 방법은 가장 느리게 나오도록 일부러 'k', 'k'를 입력으로 넣었습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# execution time comparison 
# of two methods 
 
import time
 
= 1000000
 
t0 = time.time()
for _ in range(N):
    calProdUnitQuat('k''k')
print(f'If you want to look really sexy, it takes {time.time()-t0:5.2f} s.')
 
t0 = time.time()
for _ in range(N):
    calProdUnitQuat2('k''k')
print(f'If you do NOT care the ugliness, it takes {time.time()-t0:5.2f} s.')
cs

 

결과는?

 

Ugliness bests sexiness, which is waaaaaay too slow.

못생긴게 15배 빠르군요.... 좀 못생기면 어떻습니까. 어차피 안생기는데.... 헣허헣허허허ㅓㅓㅎㅎㅎ~~

 

 

- 게으른 파이썬

 

 

덧. 참고로 못생긴 방법 테스트에 가장 빠른 패턴인 '1', '1'을 입력하면 'k', 'k'보다 3배 빨라집니다. (...)

댓글