我有一個任意大小的浮點向量。我想調整浮點數以使其滿足條件abs(float) <= 0.5.小數部分應保留,盡管它可能與原始值不同,因此設定“x = 0.5”是不正確的。如果浮點數接近整數,則丟棄它(輸入浮點數不得為整數或在任意精度范圍內接近一)。
這是我寫的,但代碼看起來有些復雜。我想知道是否有辦法讓它更優雅/更高效,或者我可能錯過了一些至關重要的東西。
輸入:浮點數
輸出:調整浮點 x,使 fabs(x) <= 0.5
整數部分的例子
- -5.3 -> -0.3(取小數部分,如果 abs(fractional) <= 0.5)
- -5.8 -> 0.2(添加最接近的整數,向上舍入,相對于絕對值)。
- 5.3 -> 0.3
- 5.8 -> -0.2(減去,但向下舍入)
- -5.5 -> -0.5(此處保留符號)
- 5.5 -> 0.5(此處保留符號)
只有小數部分的示例
0.3 -> 0.3
0.8 -> -0.2(減去 1)
-0.3 -> -0.3
-0.8 -> 0.2(加 1)
角落案例
- 任何整數 -> 0
- 0.5 -> 0.5
- -0.5 -> -0.5
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>
float scale(float x)
{
const auto integerPart = std::abs(static_cast<std::int32_t>(x));
const auto fractionalPart = std::fabs(x - static_cast<std::int32_t>(x));
if (x < 0) {
if (integerPart == 0) {
if (fractionalPart > 0.5) {
x = 1;
}
}
else {
x = integerPart (fractionalPart > 0.5 ? 1 : 0);
}
}
else {
if (integerPart == 0) {
if (fractionalPart > 0.5) {
x -= 1;
}
} else {
x -= integerPart (fractionalPart > 0.5 ? 1 : 0);
}
}
return x;
}
int main() {
std::vector<float> floats(10000);
static std::default_random_engine e;
static std::uniform_real_distribution<float> distribution(-5, 5);
std::generate(floats.begin(),
floats.end(),
[&]() { return distribution(e); });
for (std::size_t i = 0; i < floats.size(); i) {
floats[i] = scale(floats[i]);
}
std::cout << std::boolalpha
<< std::all_of(floats.cbegin(),
floats.cend(),
[&](const float x){ return std::fabs(x) <= 0.5; }) << "\n";
}
符號保留在這里是相關的,如果小數部分超過 0.5,則結果值的符號反轉。
謝謝你。
uj5u.com熱心網友回復:
您可以使用該floor功能來減少分支的數量:
#include <iostream>
#include <cmath>
float scale(float x) {
bool neg = std::signbit(x);
x -= std::floor(x 0.5);
if (!neg && x == -0.5) {
return 0.5;
} else {
return x;
}
}
int main() {
std::cout << "-1.23 " << scale(-1.23) << std::endl;
std::cout << "-0.5 " << scale(-0.5) << std::endl;
std::cout << "0.123 " << scale(0.123) << std::endl;
std::cout << "0.5 " << scale(0.5) << std::endl;
std::cout << "1.23 " << scale(1.23) << std::endl;
}
-1.23 -0.23
-0.5 -0.5
0.123 0.123
0.5 0.5
1.23 0.23
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/475515.html
