python - 如何在不使用标准函数的情况下合理化分数?
问题描述
那么,如何在不使用标准函数模块的情况下编写一个找到一个有理数的python代码,这个有理数接近一个分数,比如f?
例如,3.14=22/7
分子和分母也有限制,例如:
- 分子不能大于 p
- 分母不能大于 q。
我的工作:
# calculates i/j upto a precision of 0.001 closer to f.
while( abs((i/j)-f)> 0.001 and i<p, j<q):
j=j-1
i =?,
现在我很困惑,我应该如何修改我的 i 和 j 以使其工作?我可以以任何方式使用 Newton Raphson 算法吗?
解决方案
Pythons 标准库为此提供了一个模块:
print(fractions.Fraction.from_float(math.pi).limit_denominator(30))
输出
22/7
蛮力方法:
import math
def approx(number, p):
best = None
best_dist = number
for d in range(1, p + 1):
n0 = int(d / number)
for n in (n0 -1, n0, n0 + 1):
if n <= 0:
continue
dist = abs(number - d / n)
if dist < best_dist:
best_dist = dist
best = (d, n)
return best
print(approx(math.pi, 30))
输出
(22, 7)
然后还有第三种选择:https ://www.johndcook.com/blog/2010/10/20/best-rational-approximation/
推荐阅读
- javascript - 我有 2 个状态,但即使我只 setState 其中一个,它们都在更新
- python - 任何可用于在 Python 中开发移动应用程序的框架?
- azure - Azure 认知搜索引发 System.NullReferenceException
- php - 如何在特征中键入提示“$this”属性
- flutter - 未找到 Flutter 网络图像图像
- android - ItemTouchHelper.Callback.getDefaultUIUtil().onDraw() 改变 z-index
- c# - 如何使用启动表单应用程序打开 API 控制器?
- node.js - 如何在自定义 Jest 节点环境中使用 ES6?
- python - 如何查找用户在服务器 Discord.py 中发送的消息数
- c# - Entity Framework Core 迁移问题与动态连接字符串取决于标头值和另一个数据库