Use more decimals in Python

前端 未结 2 406
南笙
南笙 2021-01-19 04:17

I already have a code which uses the bisection method to determine the value of something, the problem is that I need a value so precise, more than 15 decimals, and at some

2条回答
  •  情书的邮戳
    2021-01-19 04:42

    You are asking if you can change the Python builtin type of floating point literals from float to (for example) decimal.Decimal. You can't do that.

    Other things to consider

    If decimal.Decimal is central to your code, you could import it with a shorter name:

    from decimal import Decimal as Dec
    x1 = Dec('0.234')
    y1 = Dec('4.32')
    x2 = Dec('4.321')
    y2 = Dec('5.87')
    

    Type annotations can help you to not miss conversions:

    def distance(x1: Dec, y1: Dec, x2: Dec, y2: Dec) -> Dec:
        return Dec.sqrt((x2 - x1)**2 + (y2 - y1)**2)
    

    If precision is important, initialize decimal.Decimal with a string instead of float. Floats can't exactly represent simple numbers, like for example 0.2:

    >>> Dec(0.2)
    Decimal('0.200000000000000011102230246251565404236316680908203125')
    >>> Dec('0.2')
    Decimal('0.2')
    

    There is probably a limited number of places where you have to convert to Decimal. Most operations on Decimal either gives a new Decimal, or throws an exception.

    >>> d = distance(x1, y1, x2, y2)
    >>> d
    Decimal('4.371048958774083555277441787')
    >>> (d + x1*x2 + y1*y2**2) / 100
    Decimal('1.542359709587740835552774418')
    

    I know this is not perfect, but it might help.

提交回复
热议问题