Python中不准确的对数

2022-10-19Python开发问题
4

本文介绍了Python中不准确的对数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我每天都在公司使用 Python 2.4.我使用了标准数学库中的通用对数函数log",当我输入 log(2**31, 2) 时,它返回 31.000000000000004,这让我觉得有点奇怪.

I work daily with Python 2.4 at my company. I used the versatile logarithm function 'log' from the standard math library, and when I entered log(2**31, 2) it returned 31.000000000000004, which struck me as a bit odd.

我对 2 的其他幂也做了同样的事情,而且效果很好.我跑了 'log10(2**31)/log10(2)' 得到了 31.0 轮

I did the same thing with other powers of 2, and it worked perfectly. I ran 'log10(2**31) / log10(2)' and I got a round 31.0

我尝试在 Python 3.0.1 中运行相同的原始函数,假设它已在更高级的版本中得到修复.

I tried running the same original function in Python 3.0.1, assuming that it was fixed in a more advanced version.

为什么会这样?Python中的数学函数是否可能存在一些不准确之处?

Why does this happen? Is it possible that there are some inaccuracies in mathematical functions in Python?

推荐答案

这对于计算机算术来说是意料之中的.它遵循特定规则,例如 IEEE 754,可能与您所学的数学不符在学校.

This is to be expected with computer arithmetic. It is following particular rules, such as IEEE 754, that probably don't match the math you learned in school.

如果这确实很重要,请使用 Python 的 十进制类型.

If this actually matters, use Python's decimal type.

例子:

from decimal import Decimal, Context
ctx = Context(prec=20)
two = Decimal(2)
ctx.divide(ctx.power(two, Decimal(31)).ln(ctx), two.ln(ctx))

这篇关于Python中不准确的对数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10