[Python] Issue with log10(x) and Recovering Large Numbers Accurately

Discussão em 'Python' iniciado por Stack, Maio 10, 2025.

  1. Stack

    Stack Membro Participativo

    I’m having a problem with using log10(x) to compress large numbers. When I convert a large number using math.log10(x) and then try to recover it with 10 ** log10(x), I always get a result that’s slightly different from the original number due to floating-point precision limits.

    Here’s a simple example in Python:

    import math

    original = 1180591620810475438080
    log_value = math.log10(original)
    recovered = 10 ** log_value

    print(f"Original: {original}")
    print(f"log10(x): {log_value}")
    print(f"Recovered: {recovered}")
    print(f"Difference: {abs(original - recovered)}")


    Output:

    log10(x): 21.072099696512918
    Recovered: 1.1805916208104748e+21
    Difference: 786432.0


    Sometimes the difference is small, but when I work with extremely large values or need high accuracy, this small error becomes significant.

    Is there any way to control or minimize this difference? Maybe with higher-precision libraries like decimal or mpmath, or completely different approaches to map large numbers into a smaller space with less loss?

    Thanks in advance!

    Continue reading...

Compartilhe esta Página