Stay hungry, Stay foolish

0.1 + 1.1 != 1.2 / Ruby에서 Float 계산하기 본문

Ruby on Rails

0.1 + 1.1 != 1.2 / Ruby에서 Float 계산하기

Jake2 2022. 8. 17. 00:17

decimal 로 설정하기 싫었으나 어찌 표현할 방법이 없어서 decimal 로 저장한 column 이 생겼다.

출력해보니 0.5 => 0.5e0 같이 지수로 저장되어 있더라..

 

컴퓨터에서 decimal 로 연산하면 100% 정확한 값을 얻기는 어렵다. 예를 들어 0.1 + 1.1 == 1.2 -> false 가 나온다.

이렇다고 한다... 왜일까


실수의 저장 

컴퓨터는 모두 2진수로 데이터를 저장하고 통신한다.

정수의 경우에는 2 -> 00000010, 20 -> 00001100 이런식으로 2진수로 저장하는데 무리가 없다. 하지만 실수의 경우에는?

2의-1승 은 0.5 -2승은 0.25 -3승은 0.125 -4승은 0.0625 ...

10진수 0.125 는 2진수 0.001 로 표현하면 된다. 하지만 10진수 0.1 은 0.000110011 .... 0.1 을 정확하게 표현할 수가 없다.

위 예시는 메모리에 32-bit 를 할당한 예시인데 저 저장되고 더 저장할 수 없이 버려지는 부분의 수치들 때문에 미세한 오차가 발생하는 것이다.


Ruby에서는?

15.2.9 Float
15.2.9.1 General description
Instances of the class Float represent floating-point numbers. The precision of the value of an instance of the class Float is implementation-defined; however, if the underlying system of a conforming processor supports IEC 60559, the representation of an instance of the class Float shall be the 64-bit double format as specified in IEC 60559, 3.2.2.

ruby 에서는 64-bit double format을 이용한다 한다.

ruby에서는 정확한 값을 구하기 위해 정수형으로 만들어 계산 해주거나 BigDecimal 을 이용하면 된다.

BigDecimal provides similar support for very large or very accurate floating point numbers.

 

 

 

 

ref.

http://www.tcpschool.com/cpp/cpp_datatype_floatingPointNumber

https://www.youtube.com/watch?v=-GsrYvZoAdA

https://ruby-doc.org/stdlib-2.5.1/libdoc/bigdecimal/rdoc/BigDecimal.html

'Ruby on Rails' 카테고리의 다른 글

Ruby on Rails  (0) 2021.12.23
Ruby - Str method  (0) 2021.09.20
Ruby - Array method  (0) 2021.09.20
Comments