Python

Python(2) 숫자 자료형

UserDonghu 2023. 9. 8. 18:06

정수 (int)

진수 : 수를 표현하는 방법
2진수 : 0 1
8진수 : 0 1 2 3 4 5 6 7
16진수 : 0 1 2 3 4 5 6 7 8 9 a b c d e f

10진수 731 = 7 * 10^2 + 3 * 10^1 + 1 * 10^0
2진수 110 = 1  2^2 + 1 * 2^1 + 0 * 2^0

쉽게 계산하는 법
10진수 15를 2진수로 표현하면?
16이 2의 5승이므로 10000 -1 == 1111

 

# 2진수
x = 0b110
print(x) # 6 
print(type(x))# <class 'int'>

# 8진수
x = 0o110
print(x) # 72
print(type(x)) # <class 'int'>

# 16진수
x = 0x110
print(x) # 272
print(type(x)) # <class 'int'>

bin(15) # '0b1111'
oct(15) # '0o17'
hex(15) # '0xf'

 

새로운 자료형 x를 만났을 때, 꼭 해봐야 될것.

x = 10 # 새로운 자료형
print(type(x)) # 검색 키워드 <class 'int'>
print(dir(x)) # 대략적인 속성을 알 수 있습니다. ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']



# 매직 메서드: 이 타입에 속성을 정의
abs(-5) # '__abs__'
5 + 5   # '__add__'
5 and 5 # '__and__'
bool(5) # '__bool__'
5 == 5  # '__eq__'

# 메서드: 이 타입에서 변수를 다룰 수 있는 여러 기능을 제공
# 'as_integer_ratio',
# 'bit_count',
# 'bit_length',
# 'conjugate',
# 'denominator',
# 'from_bytes',
# 'imag',
# 'numerator',
# 'real',
# 'to_bytes'

 

x = 5
x.bit_count() # 이걸 사용할 일은 평생에 한 번도 없을 수도 있음..
# 1001, 2진수로 표현하면 1이 2개
# 파이썬의 속도를 위해서 정수의 메모리 미리 적재
# -5 ~ 256
x = 256
y = 256

print(id(x), id(y)) # 132415440838864 132415440838864

 

실수 (float)

 

x = 10.0
y = 2
result = x * y
print(result) # 20.0 실수X정수 = 실수
print(type(result)) # <class 'float'>

 

# float의 특수값
# 이 특수값은 사용을 하니 기억
# 정렬과 같은 파트에서 초깃값으로 사용
float("inf") > 10000000000000000000 # True
float("-inf") < -9999999999999 # True

 

# 부동소숫점 문제
print(0.1 + 0.2) # 0.30000000000000004
# 발생하는 이유? 결국 컴퓨터 연산하는 것은 10진수가 아니라 2진수인데
# 2진수 변환에서 무한수가 발생이 되므로


# 부동소숫점 문제가 발생하지 않으려면
import decimal
from fractions import Fraction
# 각각 모듈 import해서 사용
float(decimal.Decimal('.1') + decimal.Decimal('.2'))
float(fractions.Fraction('0.1') + fractions.Fraction('0.2'))

 

복소수 (complex)

x = 3 + 4j
print(x) # (3+4j)

x = 3 + 4j
print(x.real) # 3.0
print(x.imag) # 4.0

 

 

'Python' 카테고리의 다른 글

Python(6) 연산  (0) 2023.09.11
Python(5) 메서드 체이닝, 형변환  (0) 2023.09.11
Python(4) 논리 자료형, None 자료형  (0) 2023.09.11
Python(3) 문자열 자료형  (1) 2023.09.08
Python(1) 시작  (0) 2023.09.08