tun*_*h24 6 c++ math floating-point decimal
给定两个整数 X 和 Y,在 C++ 中将它们转换为 XY 浮点值的最有效方法是什么?
例如
X = 3, Y = 1415 -> 3.1415
X = 2, Y = 12 -> 2.12
Run Code Online (Sandbox Code Playgroud)
以下是截至撰写本文时所有将ints转换为 a 的解决方案在我的机器上的鸡尾酒餐巾纸基准测试结果float。
警告:我现在添加了我自己的解决方案,它似乎做得很好,因此有偏见!请仔细检查我的结果。
| 测试 | 迭代次数 | ns / 迭代 |
|---|---|---|
| @aliberro 的转换 v2 | 79,113,375 | 13 |
| @3Dave 的转换 | 84,091,005 | 12 |
| @einpoklum 的转换 | 1,966,008,981 | 0 |
| @Ripi2 的转换 | 47,374,058 | 21 |
| @TarekDakhran 的转换 | 1,960,763,847 | 0 |
-O3 -march=native -mtune=native基准代码(Github Gist)。
float sum = x + y / pow(10,floor(log10(y)+1));
Run Code Online (Sandbox Code Playgroud)
log10返回其参数的日志(以 10 为底)。对于 1234,这将是 3 分。
打破这个:
log10(1234) = 3.091315159697223
floor(log10(1234)+1) = 4
pow(10,4) = 10000.0
3 + 1234 / 10000.0 = 3.1234.
Run Code Online (Sandbox Code Playgroud)
但是,正如@einpoklum 指出的那样,log(0)是NaN,所以你必须检查一下。
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
float foo(int x, unsigned int y)
{
if (0==y)
return x;
float den = pow(10,-1 * floor(log10(y)+1));
return x + y * den;
}
int main()
{
vector<vector<int>> tests
{
{3,1234},
{1,1000},
{2,12},
{0,0},
{9,1}
};
for(auto& test: tests)
{
cout << "Test: " << test[0] << "," << test[1] << ": " << foo(test[0],test[1]) << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
查看可运行版本:https : //onlinegdb.com/rkaYiDcPI
带测试输出:
测试:3,1234:3.1234
测试:1,1000:1.1 测试:2,12:
2.12
测试:0,0:0
测试:9,1:9.1
编辑
删除除法运算的小修改。
简单且非常快速的解决方案是将值x和转换y为字符串,然后将它们连接起来,然后将结果转换为浮点数,如下所示:
#include <string>
#include <iostream>
std::string x_string = std::to_string(x);
std::string y_string = std::to_string(y);
std::cout << x_string +"."+ y_string ; // the result, cast it to float if needed
Run Code Online (Sandbox Code Playgroud)