Python/2.7 information

분수 관련 fraction과 struct모듈

qkqhxla1 2015. 3. 28. 17:18

fraction모듈은 파이썬에서 정밀한 분수 처리 등에 이용된다.

docs : https://docs.python.org/2/library/fractions.html#fractions.Fraction

간단한 예제.

# -*- encoding: cp949 -*-
from fractions import Fraction
print Fraction(1,5) #인자가 2개일경우 첫번째인자는 분자, 두번째인자는 분모.
print Fraction(1.5) #인자가 하나일경우 해당 소수를 분수로 변환해줌.
print sum([Fraction(1,i) for i in range(1,101)]) #1/1 + 1/2+ 1/3 + 1/4.... 1/100의 분수를 구하는 예제.
print float(sum([Fraction(1,i) for i in range(1,101)])) #위의 값을 소수로 표현.

해당 모듈을 살펴보면서 왠지 이렇게 정교하게 분수를 나타낼수 있는데 정교하게 소숫점을 나타낼수 있는 모듈이나 클래스도 있지 않을까?? 하고 찾아봤는데 그건 안된단다. 단순히 소숫점 표현은 float()로 감싸서 해야 한다.

https://docs.python.org/2/tutorial/floatingpoint.html

http://stackoverflow.com/questions/4841732/python-convert-fraction-to-decimal

스택오버플로우를 찾아봐도 그냥 float로 변환했음.




struct는 매번 찾아보기 귀찮아서 여기다가 복붙.. 많이 쓰는거기 때문에 별 설명은 없.


struct.

참조할 링크.

https://docs.python.org/2.7/library/struct.html?highlight=struct#module-struct


http://blog.naver.com/shw20319/20180617590




외울거 : <는 리틀앤디안, 대문자면 unsigned형으로 판별, 나머지는 그때그때 참조할 것.

추가 예정.

'Python > 2.7 information' 카테고리의 다른 글

파이썬 출력 format관련.  (0) 2015.04.16
wargame.kr pyc_decompile  (0) 2015.03.29
파이썬을 더 멋있게 쓰기위한 함수, itertools 모듈  (0) 2015.03.05
*args, **kwargs  (0) 2015.03.01
pyv8 (python javascript engine)  (0) 2015.02.24