dividindo um número em partes inteiras e decimais

92

Existe uma maneira pitônica de dividir um número 1234.5678em duas partes, (1234, 0.5678)ou seja, a parte inteira e a parte decimal?

AA duplo
fonte

Respostas:

143

Use math.modf:

import math
x = 1234.5678
math.modf(x) # (0.5678000000000338, 1234.0)
Mhyfritz
fonte
2
Perfeito! Funciona muito bem com negativos também! Obrigado
Double AA
1
depois de aplicar math.modf (x), como posso lidar com os valores dos resultados? Por exemplo, se eu atribuir 1234,0 a uma variável, como posso fazer isso?
hakiko
3
dez, int = math.modf (1234.5678)
gbtimmon
19
Não use intcomo um nome de variável, ele substituirá a intfunção.
Holloway
2
@Trengot - Use int_se você deve ter uma variável que, quando lida em voz alta, é chamada de "int".
ArtOfWarfare
62

Podemos usar uma função interna não famosa; divmod:

>>> s = 1234.5678
>>> i, d = divmod(s, 1)
>>> i
1234.0
>>> d
0.5678000000000338
utdemir
fonte
4
Fornece resultados possivelmente não intuitivos para números negativos: divmod(-4.5,1)fornece -5,0 e 0,5. Usar divmod(-4.5, -1)dá 4.0 e -0.5.
Holloway
@Holloway não é pouco intuitivo, vem de regras matemáticas: en.wikipedia.org/wiki/Floor_and_ceiling_functions :)
Sviatoslav V.
46
>>> a = 147.234
>>> a % 1
0.23400000000000887
>>> a // 1
147.0
>>>

Se você quiser que a parte inteira seja um inteiro e não um flutuante, use int(a//1). Para obter a tupla em uma única passagem:(int(a//1), a%1)

EDITAR: Lembre-se de que a parte decimal de um número flutuante é aproximada , então se você quiser representá-lo como um humano faria, você precisa usar a biblioteca decimal

Mac
fonte
5
Resultados um pouco confusos para números negativos -2.25 // 1 == -3.0e -2.25 % 1 == 0.75. Isso pode ser o que o OP deseja, já que parte interna + parte decimal ainda é igual ao valor original. Em contraste math.modf(-2.25) == (-0.25, -2.0),.
Andrew Clark
@Andrew - bom ponto! Acho que a resposta de @mhyfritz é melhor, de qualquer forma!
mac
Legal - acho que esta seria a maneira mais rápida de todas as mostradas aqui, levando em consideração a advertência de Andrew Clark para números negativos
jacanterbury
14
intpart,decimalpart = int(value),value-int(value)

Funciona para números positivos.

Mark Ransom
fonte
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
iMom0
1
@ iMom0 - Consulte docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html e várias perguntas neste site sobre a precisão do ponto flutuante.
Mark Ransom,
7

Esta variante permite obter a precisão desejada:

>>> 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)
dann
fonte
4

Isso também funciona para mim

>>> val_int = int(a)
>>> val_fract = a - val_int
Vergonha
fonte
1

É assim que eu faço:

num = 123.456
split_num = str(num).split('.')
int_part = int(split_num[0])
decimal_part = int(split_num[1])
santo bebedor
fonte
4
Dependendo do caso de uso, isso provavelmente não funcionará para números com zero após a casa decimal (por exemplo, 123.0456)
Jon
Você está certo: depende do caso de uso. Se você tentar com 123.0456, o resultado é int_part = 123 e decimal_part = 456. Em meus casos de uso, achei "a remoção de zero" útil :)
holydrinker
0

Se você não se importa em usar o NumPy, então:

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)
kmario23
fonte
0

Eu vim com duas declarações que podem dividir números positivos e negativos em inteiros e frações sem comprometer a precisão (estouro de bits) e velocidade.

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

Por exemplo 100.1323-> 100, 0.1323ou -100.1323-> -100,-0.1323

Teste rápido

O teste de desempenho mostra que as duas instruções são mais rápidas do que math.modf, contanto que não sejam colocadas em suas próprias funções ou métodos.

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()')

Resultado:

         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:

A instrução pode ser mais rápida com o módulo, mas o módulo não pode ser usado para dividir números negativos em inteiros e partes fracionárias.

i, f = int(x), x*1e17%1e17/1e17 # x can not be negative
Diblo Dk
fonte