菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 3 教程
Python3 教程 Python3 简介 Python3 环境搭建 Python3 VScode Python3 基础语法 Python3 基本数据类型 Python3 数据类型转换 Python3 解释器 Python3 注释 Python3 运算符 Python3 数字(Number) Python3 字符串 Python3 列表 Python3 元组 Python3 字典 Python3 集合 Python3 条件控制 Python3 循环语句 Python3 编程第一步 Python3 推导式 Python3 迭代器与生成器 Python3 with Python3 函数 Python3 lambda Python3 装饰器 Python3 数据结构 Python3 模块 Python __name__ Python3 输入和输出 Python3 File Python3 OS Python3 错误和异常 Python3 面向对象 Python3 命名空间/作用域 Python 虚拟环境的创建 Python 类型注解 Python3 标准库概览 Python3 实例 Python 测验

Python3 高级教程

Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQt Python for 循环 Python while 循环
(追記) (追記ここまで)

Python math.nextafter() 函数

Python math 模块 Python math 模块


在浮点数计算中,了解相邻浮点数之间的关系非常重要。计算机中的浮点数是离散的,相邻两个浮点数之间有一个最小的间隔。

math.nextafter() 是 Python 3.9 引入的函数,用于返回从 x 朝 y 方向前进指定浮点步数后的值。

单词释义: nextafter 意为"下一个之后"。


基本语法与参数

语法格式

import math
math.nextafter(x, y[, steps])

参数说明

  • x: 起始浮点数
  • y: 目标方向
  • steps(可选): 步数,默认为 1

返回值

返回从 x 沿 y 方向前进 steps 步后的浮点数


实例

示例 1:获取相邻浮点数

实例

import math

next_val = math.nextafter(1.0, math.inf)
print(f"1.0 的下一个浮点数: {next_val}")
print(f"差值: {next_val - 1.0}")

prev_val = math.nextafter(1.0, -math.inf)
print(f"\n1.0 的前一个浮点数: {prev_val}")
print(f"差值: {1.0 - prev_val}")

运行结果:

1.0 的下一个浮点数: 1.0000000000000002
差值: 2.220446049250313e-16
1.0 的前一个浮点数: 0.9999999999999999
差值: 1.1102230246251565e-16

示例 2:steps 参数

实例

import math

print("前进 10 步:", math.nextafter(1.0, math.inf, 10))
print("负数步数:", math.nextafter(1.0, -math.inf, -5))

运行结果:

前进 10 步: 1.0000000000000007
负数步数: 0.9999999999999996

示例 3:特殊值

实例

import math

print("无穷大:", math.nextafter(math.inf, 0))
print("0 之后:", math.nextafter(0.0, 1.0))
print("负零:", math.nextafter(-0.0, 1.0))

运行结果:

无穷大: 1.7976931348623157e+308
0 之后: 5e-324
负零: 5e-324

示例 4:计算 ULP

实例

import math

for x in [1.0, 2.0, 100.0]:
ulp = math.nextafter(x, math.inf) - x
print(f"ULP({x}) = {ulp}")

运行结果:

ULP(1.0) = 2.220446049250313e-16
ULP(2.0) = 4.440892098500626e-16
ULP(100.0) = 2.8421709430404007e-14

注意事项

  • Python 3.9+ 才有此函数
  • steps 参数也是 Python 3.9 新增
  • 可用于理解浮点数精度限制

Python math 模块 Python math 模块

AI 思考中...

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /