std::lerp
定义于头文件 <cmath> |
||
(1) | ||
constexpr float lerp( float a, float b, float t ) noexcept; constexpr double lerp( double a, double b, double t ) noexcept; |
(始于 C++20) (截至 C++23) |
|
constexpr /* floating-point-type */ lerp( /* floating-point-type */ a, |
(始于 C++23) | |
定义于头文件 <cmath> |
||
template< class Arithmetic1, class Arithmetic2, class Arithmetic3 > constexpr /* common-floating-point-type */ |
(A) | (始于 C++20) |
[
0,
1)
范围内(否则为 线性外推),即 a+t(b−a) 的结果,并考虑了浮点计算的精度。 该库为所有 cv-unqualified 浮点类型提供重载作为参数 a, b 和 t 的类型。(始于 C++23)目录 |
[编辑] 参数
a, b, t | - | 浮点值或整数值 |
[编辑] 返回值
a + t(b − a)
当 std::isfinite(a) && std::isfinite(b) 为 true 时,保证以下属性
- 如果 t == 0,则结果等于 a。
- 如果 t == 1,则结果等于 b。
- 如果 t >= 0 && t <= 1,则结果是有限的。
- 如果 std::isfinite(t) && a == b,则结果等于 a。
- 如果 std::isfinite(t) || (b - a != 0 && std::isinf(t)),则结果不是 NaN。
设 CMP(x, y) 在 x > y 时为 1,在 x < y 时为 -1,否则为 0。 对于任何 t1 和 t2,以下各项的乘积
- CMP(std::lerp(a, b, t2), std::lerp(a, b, t1)),
- CMP(t2, t1),和
- CMP(b, a)
是非负的。(也就是说,std::lerp
是单调的。)
[编辑] 注释
附加重载不需要完全按照 (A) 提供。 它们只需要足以确保对于它们的第一个参数 num1、第二个参数 num2 和第三个参数 num3
|
(截至 C++23) |
如果 num1、num2 和 num3 具有算术类型,则 std::lerp(num1, num2, num3) 具有与 std::lerp(static_cast</*common-floating-point-type*/>(num1), 如果不存在具有最高等级和子等级的此类浮点类型,则重载解析不会从提供的重载中产生可用的候选对象。 |
(始于 C++23) |
特性测试宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_interpolate |
201902L |
(C++20) | std::lerp , std::midpoint |
[编辑] 示例
#include <cassert> #include <cmath> #include <iostream> float naive_lerp(float a, float b, float t) { return a + t * (b - a); } int main() { std::cout << std::boolalpha; const float a = 1e8f, b = 1.0f; const float midpoint = std::lerp(a, b, 0.5f); std::cout << "a = " << a << ", " << "b = " << b << '\n' << "midpoint = " << midpoint << '\n'; std::cout << "std::lerp is exact: " << (a == std::lerp(a, b, 0.0f)) << ' ' << (b == std::lerp(a, b, 1.0f)) << '\n'; std::cout << "naive_lerp is exact: " << (a == naive_lerp(a, b, 0.0f)) << ' ' << (b == naive_lerp(a, b, 1.0f)) << '\n'; std::cout << "std::lerp(a, b, 1.0f) = " << std::lerp(a, b, 1.0f) << '\n' << "naive_lerp(a, b, 1.0f) = " << naive_lerp(a, b, 1.0f) << '\n'; assert(not std::isnan(std::lerp(a, b, INFINITY))); // lerp here can be -inf std::cout << "Extrapolation demo, given std::lerp(5, 10, t):\n"; for (auto t{-2.0}; t <= 2.0; t += 0.5) std::cout << std::lerp(5.0, 10.0, t) << ' '; std::cout << '\n'; }
可能输出
a = 1e+08, b = 1 midpoint = 5e+07 std::lerp is exact?: true true naive_lerp is exact?: true false std::lerp(a, b, 1.0f) = 1 naive_lerp(a, b, 1.0f) = 0 Extrapolation demo, given std::lerp(5, 10, t): -5 -2.5 0 2.5 5 7.5 10 12.5 15
[编辑] 参见
(C++20) |
两个数字或指针之间的 midpoint (函数模板) |