Esiste un modo pitonico per dividere un numero come 1234.5678in due parti, (1234, 0.5678)cioè la parte intera e la parte decimale?
Risposte:
Usa math.modf:
import math
x = 1234.5678
math.modf(x) # (0.5678000000000338, 1234.0)
intcome nome di variabile, sovrascriverà la intfunzione.
int_se devi avere una variabile che, se letta ad alta voce, si chiama "int".
Possiamo usare una funzione incorporata non famosa; divmod:
>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338
divmod(-4.5,1)dà -5,0 e 0,5. Utilizzando divmod(-4.5, -1)dà 4.0 e -0.5.
>>> a = 147.234
>>> a % 1
0.23400000000000887
>>> a // 1
147.0
>>>
Se vuoi che la parte intera sia un numero intero e non un float, usa int(a//1)invece. Per ottenere la tupla in un unico passaggio:(int(a//1), a%1)
EDIT: ricorda che la parte decimale di un numero float è approssimativa , quindi se vuoi rappresentarlo come farebbe un essere umano, devi usare la libreria decimal
-2.25 // 1 == -3.0e -2.25 % 1 == 0.75. Questo potrebbe essere ciò che l'OP vorrebbe, poiché la parte int + la parte decimale è ancora uguale al valore originale. Al contrario, math.modf(-2.25) == (-0.25, -2.0).
intpart,decimalpart = int(value),value-int(value)
Funziona per numeri positivi.
In [1]: value = 1.89 In [2]: intpart,decimalpart = int(value),value-int(value) In [3]: intpart Out [3]: 1 In [4]: decimalpart Out [4]: 0.8899999999999999
Questo è il modo in cui lo faccio:
num = 123.456
split_num = str(num).split('.')
int_part = int(split_num[0])
decimal_part = int(split_num[1])
Ho creato due affermazioni che possono dividere i numeri positivi e negativi in numeri interi e frazioni senza compromettere l'accuratezza (bit overflow) e la velocità.
x = 100.1323 # A number to be divided into integers and fractions
# The two statement to divided a number into integers and fractions
i = int(x) # A positive or negative integer
f = (x*1e17-i*1e17)/1e17 # A positive or negative fraction
Ad esempio 100.1323-> 100, 0.1323o -100.1323-> -100,-0.1323
Test di velocità
Il test delle prestazioni mostra che le due istruzioni sono più veloci di math.modf, a condizione che non siano inserite nella loro funzione o metodo.
test.py:
#!/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 integers and fractions
LOOPS = range(5*10**6) # Number of loops
def scenario_a():
""" The integers (i) and the fractions (f)
come out as integer and float. """
for _ in LOOPS:
i = int(X) # -100
f = (X*1e17-i*1e17)/1e17 # -0.1323
def scenario_b():
""" The integers (i) and the fractions (f)
come out as 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():
""" Performance test 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():
for _ in LOOPS:
f, i = math.modf(X) # (-100.0, -0.13230000000000075)
def scenario_e():
""" Convert the integer part to real integer. """
for _ in LOOPS:
f, i = math.modf(X) # (-100.0, -0.13230000000000075)
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()')
Produzione:
4 function calls in 1.312 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.312 1.312 <string>:1(<module>)
1 1.312 1.312 1.312 1.312 test.py:10(scenario_a)
1 0.000 0.000 1.312 1.312 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
4 function calls in 1.887 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.887 1.887 <string>:1(<module>)
1 1.887 1.887 1.887 1.887 test.py:18(scenario_b)
1 0.000 0.000 1.887 1.887 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 2.797 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.797 2.797 <string>:1(<module>)
1 1.261 1.261 2.797 2.797 test.py:27(scenario_c)
5000000 1.536 0.000 1.536 0.000 test.py:31(modf)
1 0.000 0.000 2.797 2.797 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 1.852 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.852 1.852 <string>:1(<module>)
1 1.050 1.050 1.852 1.852 test.py:38(scenario_d)
1 0.000 0.000 1.852 1.852 {built-in method builtins.exec}
5000000 0.802 0.000 0.802 0.000 {built-in method math.modf}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000004 function calls in 2.467 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.467 2.467 <string>:1(<module>)
1 1.652 1.652 2.467 2.467 test.py:42(scenario_e)
1 0.000 0.000 2.467 2.467 {built-in method builtins.exec}
5000000 0.815 0.000 0.815 0.000 {built-in method math.modf}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
NOTA:
L'istruzione può essere più veloce con modulo, ma modulo non può essere utilizzato per dividere i numeri negativi in parti intere e frazionarie.
i, f = int(x), x*1e17%1e17/1e17 # x can not be negative