为了账号安全,请及时绑定邮箱和手机立即绑定

使用 limit 方法计算 pi 会产生意想不到的结果

使用 limit 方法计算 pi 会产生意想不到的结果

哔哔one 2023-09-05 20:34:44
我正在尝试在 python 中执行 sin 操作,这正是我正在运行的:test = math.sin(180/1000000) * 1000000 print(test)从技术上讲,这个操作给你大约 pi (3.14159265),但在 python 中,它给我 179.99999902800002。有谁知道为什么会发生这种情况?
查看完整描述

2 回答

?
元芳怎么了

TA贡献1798条经验 获得超7个赞

  • 该函数期望值以弧度为单位,而不是度数

    • 从文档来看,math.sin(x)

  • mathusing或numpy函数之间的区别在于,它将numpyarray

    • np.deg2rad([45, 90])作品

    • math.radians([45, 90])结果是TypeError

  • 如果您使用单个值,请使用该math函数,否则使用numpy.

  • Wolfram Research链接到 pi 的限制表示。

import numpy as np

import math


# convert from degrees to radians

x = np.deg2rad(180/1000000)


# make calculation

v = math.sin(x)


z = v * 1000000


# print(z)

3.1415926535846257

  • math.sin这里并没有真正做任何事情。

    • 对于小角度,sin(x) ≈ x,所以sin(π/1000000) × 1000000 ≈ π

x

[out]:

3.1415926535897933e-06


v

[out]:

3.1415926535846256e-06



查看完整回答
反对 回复 2023-09-05
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

发生这种情况是因为math.sin(x)期望 x 以弧度为单位:

math.sin(x)
    Return the sine of x radians.

为了解决这个问题,您需要首先将 x 转换为弧度,如下所示:

test = math.sin(math.radians(180)/1000000) * 1000000

输出:

3.1415926535846257

我不建议使用 NumPy,因为这个问题没有必要。math.radians()足够了。


查看完整回答
反对 回复 2023-09-05
  • 2 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信