In [319]: real = np.array([1234.5678])
In [327]: integ, deci = int(np.floor(real)), np.asscalar(real % 1)
In [328]: integ, deci
Out[328]: (1234, 0.5678000000000338)
I have come up with two statements that can divide positive and negative numbers into integer and fraction without compromising accuracy (bit overflow) and speed.
# Divide a number (x) into integer and fraction
i = int(x) # Get integer
f = (x*1e17 - i*1e17) / 1e17 # Get fraction
极速测试
The performance test shows that the two statements are faster than math.modf, as long as they are not put into their own function or method.
返回文章页面
#!/usr/bin/env python
import math
import cProfile
""" Get the performance of both statements and math.modf """
X = -100.1323 # The number to be divided into integer and fraction
LOOPS = range(5 * 10 ** 6) # Number of loops
def scenario_a():
""" Get the performance of the statements """
for _ in LOOPS:
i = int(X) # -100
f = (X*1e17-i*1e17)/1e17 # -0.1323
def scenario_b():
""" Tests the speed of the statements when integer need to be float.
NOTE: The only difference between this and math.modf is the accuracy """
for _ in LOOPS:
i = int(X) # -100
i, f = float(i), (X*1e17-i*1e17)/1e17 # (-100.0, -0.1323)
def scenario_c():
""" Tests the speed of the statements in a function """
def modf(x):
i = int(x)
return i, (x*1e17-i*1e17)/1e17
for _ in LOOPS:
i, f = modf(X) # (-100, -0.1323)
def scenario_d():
""" Tests the speed of math.modf """
for _ in LOOPS:
f, i = math.modf(X) # (-0.13230000000000075, -100.0)
def scenario_e():
""" Tests the speed of math.modf when the integer part should be integer """
for _ in LOOPS:
f, i = math.modf(X) # (-0.13230000000000075, -100.0)
i = int(i) # -100
if __name__ == '__main__':
cProfile.run('scenario_a()')
cProfile.run('scenario_b()')
cProfile.run('scenario_c()')
cProfile.run('scenario_d()')
cProfile.run('scenario_e()')
#!/usr/bin/env python
import math
import cProfile
import math2
""" Get the performance of both statements and math.modf """
X = -100.1323 # The number to be divided into integers and fractions
LOOPS = range(5 * 10 ** 6) # Number of loops
def scenario_a():
""" Tests the speed of the statements in a function using C/C++ support """
for _ in LOOPS:
i, f = math2.modf(X) # (-100, -0.1323)
def scenario_b():
""" Tests the speed of math.modf """
for _ in LOOPS:
f, i = math.modf(X) # (-0.13230000000000075, -100.0)
if __name__ == '__main__':
cProfile.run('scenario_a()')
cProfile.run('scenario_b()')
This will accomplish the task without the issue of dropping leading zeroes (like holydrinker's answer):
密码
def extract_int_decimal():
'''get the integer and decimal parts of a given number
by converting it to string and using split method
'''
num = 1234.5678
split_num = str(num).split('.')
int_part = int(split_num[0])
decimal_part = int(split_num[1]) * 10 ** -len(split_num[1])
print("integer part:",int_part)
print("decimal part:",decimal_part)
extract_int_decimal()