파이썬 부동에서 정수로 변환
기본적으로 부동 소수점을 int로 변환하고 있지만 항상 예상 값이있는 것은 아닙니다.
실행중인 코드는 다음과 같습니다.
x = 2.51
print("--------- 251.0")
y = 251.0
print(y)
print(int(y))
print("--------- 2.51 * 100")
y = x * 100
print(y)
print(int(y))
print("--------- 2.51 * 1000 / 10")
y = x * 1000 / 10
print(y)
print(int(y))
print("--------- 2.51 * 100 * 10 / 10")
y = x * 100 * 10 / 10
print(y)
print(int(y))
x = 4.02
print("--------- 402.0")
y = 402.0
print(y)
print(int(y))
print("--------- 4.02 * 100")
y = x * 100
print(y)
print(int(y))
print("--------- 4.02 * 1000 / 10")
y = x * 1000 / 10
print(y)
print(int(y))
print("--------- 4.02 * 100 * 10 / 10")
y = x * 100 * 10 / 10
print(y)
print(int(y))
결과는 다음과 같습니다 (첫 번째 값은 작업의 결과이고 두 번째 값은 동일한 작업의 int ()입니다).
--------- 251.0
251.0
251
--------- 2.51 * 100
251.0
250
--------- 2.51 * 1000 / 10
251.0
251
--------- 2.51 * 100 * 10 / 10
251.0
250
--------- 402.0
402.0
402
--------- 4.02 * 100
402.0
401
--------- 4.02 * 1000 / 10
402.0
401
--------- 4.02 * 100 * 10 / 10
402.0
401
2.51 및 4.02는 2.50-> 5.00 범위에서 이상한 동작을 유발하는 유일한 값입니다. 해당 범위의 다른 두 자리 값은 동일한 작업이 주어지면 문제없이 int로 변환됩니다.
그래서, 그 결과로 이어지는 내가 무엇을 놓치고 있습니까? 그런데 저는 Python 2.7.2를 사용하고 있습니다.
2.51 * 100 = 250.999999999997
이 int()
함수는 단순히 소수점에서 250을 제공하는 숫자를 자릅니다. 사용
int(round(2.51*100))
to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Floating-point numbers cannot represent all the numbers. In particular, 2.51 cannot be represented by a floating-point number, and is represented by a number very close to it:
>>> print "%.16f" % 2.51
2.5099999999999998
>>> 2.51*100
250.99999999999997
>>> 4.02*100
401.99999999999994
If you use int, which truncates the numbers, you get:
250
401
Have a look at the Decimal type.
Languages that use binary floating point representations (Python is one) cannot represent all fractional values exactly. If the result of your calculation is 250.99999999999 (and it might be), then taking the integer part will result in 250.
A canonical article on this topic is What Every Computer Scientist Should Know About Floating-Point Arithmetic.
>>> x = 2.51
>>> x*100
250.99999999999997
the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.
you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library http://code.google.com/p/mpmath/ :),
int
converts by truncation, as has been mentioned by others. This can result in the answer being one different than expected. One way around this is to check if the result is 'close enough' to an integer and adjust accordingly, otherwise the usual conversion. This is assuming you don't get too much roundoff and calculation error, which is a separate issue. For example:
def toint(f):
trunc = int(f)
diff = f - trunc
# trunc is one too low
if abs(f - trunc - 1) < 0.00001:
return trunc + 1
# trunc is one too high
if abs(f - trunc + 1) < 0.00001:
return trunc - 1
# trunc is the right value
return trunc
This function will adjust for off-by-one errors for near integers. The mpmath
library does something similar for floating point numbers that are close to integers.
참고URL : https://stackoverflow.com/questions/6569528/python-float-to-int-conversion
'code' 카테고리의 다른 글
Scala는 꼬리 재귀 최적화를 지원합니까? (0) | 2020.11.27 |
---|---|
Java에서 String을 char로 또는 char를 String으로 어떻게 변환합니까? (0) | 2020.11.27 |
DataTables 경고 : '0'행의 데이터 소스에서 알 수없는 매개 변수 '0'을 요청했습니다. (0) | 2020.11.27 |
Apache HttpClient API에서 CloseableHttpClient와 HttpClient의 차이점은 무엇입니까? (0) | 2020.11.27 |
NLog 항목을 vs2008 '출력'창에 어떻게 출력 할 수 있습니까? (0) | 2020.11.27 |