suddividendo un numero nelle parti intero e decimale


92

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:


143

Usa math.modf:

import math
x = 1234.5678
math.modf(x) # (0.5678000000000338, 1234.0)

2
Perfetto! Funziona alla grande anche con i negativi! Grazie
Doppio AA

1
dopo aver applicato math.modf (x) come posso gestire i valori dei risultati? Ad esempio, se assegno 1234.0 a una variabile, come posso farlo?
hakiko

3
dec, int = math.modf (1234.5678)
gbtimmon

19
Non utilizzare intcome nome di variabile, sovrascriverà la intfunzione.
Holloway

2
@Trengot - Usa int_se devi avere una variabile che, se letta ad alta voce, si chiama "int".
ArtOfWarfare

62

Possiamo usare una funzione incorporata non famosa; divmod:

>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338

4
Fornisce risultati possibilmente non intuitivi per numeri negativi: divmod(-4.5,1)dà -5,0 e 0,5. Utilizzando divmod(-4.5, -1)dà 4.0 e -0.5.
Holloway

@Holloway non è intuitivo, deriva da regole matematiche: en.wikipedia.org/wiki/Floor_and_ceiling_functions :)
Sviatoslav V.

46
>>> 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


5
Risultati leggermente confusi per i numeri negativi -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).
Andrew Clark

@Andrew - buon punto! Penso che la risposta di @ mhyfritz sia migliore, comunque!
mac

Bello - Penso che questo sarebbe il modo più veloce di quelli mostrati qui tenendo presente l'avvertenza di Andrew Clark per i numeri negativi
jacanterbury


7

Questa variante consente di ottenere la precisione desiderata:

>>> a = 1234.5678
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e0)
(1234, 0.0)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e1)
(1234, 0.5)
>>> (lambda x, y: (int(x), int(x*y) % y/y))(a, 1e15)
(1234, 0.5678)

4

Funziona anche per me

>>> val_int = int(a)
>>> val_fract = a - val_int

1

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])

4
A seconda del caso d'uso, questo probabilmente non funzionerà per i numeri con zero dopo la cifra decimale (ad esempio 123.0456)
Jon

Hai ragione: dipende dal caso d'uso. Se lo provi con 123.0456 il risultato è int_part = 123 e decimal_part = 456. Nei miei casi d'uso ho trovato utile "la rimozione dello zero" :)
holydrinker

0

Se non ti dispiace usare NumPy, allora:

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)

0

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
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.