在Python中提高浮点精度 [英] Increasing floating point precision in Python

查看:651
本文介绍了在Python中提高浮点精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,使用以下代码计算pi的莱布尼兹近似值:

I was working on a project to compute the Leibniz approximation for pi with the below code:

def pi(precision):
    sign = True
    ret = 0
    for i in range(1,precision+1):
        odd = 2 * i - 1
        if sign:
            ret += 1.0 / odd
        else:
            ret -= 1.0 / odd
        sign = not sign
    return ret

但是,输出值始终为12位数字.如何提高计算的精度(例如,更多位数)? Python是否支持更精确的浮点,还是我必须使用一些外部库?

However, the output value was always was 12 digits long. How can I increase the precision (e.g. more digits) of the calculation? Does Python support more precise floating points, or will I have to use some external library?

推荐答案

尝试使用Decimal.

阅读任意精度基本数学函数(Python) 原始 了解更多信息

Read Arbitrary-precision elementary mathematical functions (Python)original for more information

这篇关于在Python中提高浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆