c++ - 如何在 C++ 中实现 Fortran 间距()函数?
问题描述
我从 Fortran 转换为 C++ 的代码包含该spacing(x)
函数。根据描述,spacing(x)
返回
给定类型的两个数字之间的最小距离
和
确定参数 X 和最近的相同类型的相邻数字之间的距离。
是否有 C++ 等效函数,或者,如果没有,我如何在 C++ 中实现该函数?
解决方案
使用SPACING
as确定参数 X 和最近的相同类型的相邻数字之间的距离,使用nexttoward()
。
upper = nexttoward(x, INFINITY) - x;
lower = x - nexttoward(x, -INFINITY);
spacing = fmin(upper, lower);
upper != lower
在某些情况下:例如x
是 2 的幂。
可能需要一些工作来处理缺乏真正 INFINITY 的实现。
或者
if (x > 0) {
spacing = x - nexttoward(x, 0);
} else {
// 1.0 used here instead of 0 to handle x==0
spacing = nexttoward(x, 1.0) - x;
}
或者
// Subtract next smaller-in-magnitude value. With 0, use next toward 1.
spacing = fabs(x - nexttoward(x, !x));
我怀疑nextafter()
会工作得一样好,或者比,nexttoward()
。
推荐阅读
- java - 为什么 java awt 应用程序不使用自定义协议处理程序在 osx 上发布焦点?
- javascript - 模拟用户单击以使元素出现在 DOM 中
- jquery - Signal R ASP.Net(当服务器访问应用程序时开始挂起)
- javascript - 从那一刻起只检索 YYYY-MM-DD
- symfony - 如何在命令中控制繁重的进程
- java - Spring Boot 和 Jersey 产生 ClassNotFound
- java - Javafx 条形图 X 轴在更新数据时无法正确缩放
- php - 如何在属于同一类的模型上使用 Laravel 急切加载
- spring-boot - Spring Security Oauth2 使用 @FrameworkEndpoint 注销
- javascript - javascript 中的 Object.assign(object1[i])