gpt4 book ai didi

c++ - 交易时如何防止数字四舍五入?

转载 作者:行者123 更新时间:2023-12-03 07:00:22 25 4
gpt4 key购买 nike

我试图用小数获取 10 到 20 之间的随机数,首先我取整数部分,然后取小数部分,这样整数部分的概率有更大的变化可能性,然后是小数部分,但是当添加两部分开始四舍五入,我不希望它被四舍五入,因为我想获得精确的小数位数,在这种情况下为 7 个小数位。

#include<iostream>
#include<math.h>
double random_decimal(int inicio, int fin, int numero_decimales)
{
double int_part = (rand() % (inicio + 1 - fin) + inicio);
int num = pow(10, numero_decimales);
double decimal_part = (double)(rand() % (1 - num)) / num;
cout << "Int: "<< int_part << " Dec: "<< decimal_part << " Sum: "<< int_part + decimal_part << endl;
return (double)(int_part + decimal_part);
}
int main()
{
int ed;
double ps, estat;
for(int i = 0; i < 10; i++)
{
double x = random_decimal(10, 20, 7);
}
}

最佳答案

首先,不要使用 rand()如果您可以使用 C++11 random 之一类:https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
例如:

std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(10.0,20.0);
至于“四舍五入”或“精确的小数位数” - 我不会担心。具体来说:

https://peter.bloomfield.online/decimal-places-in-a-floating-point-number/

Significant figures != decimal places

It’s easy to make the mistake of thinking that the code above answersour decimal places question. However, consider the following numbers:

0.12345123451234512345
0.00000000000000012345

Both of them are written with 20 decimal places. However, the secondone would only require 5 significant figures (or the equivalent of 5decimal digits in the mantissa). The extra leading zeroes after thedecimal point can be represented by simply decreasing the exponent(i.e. making it more negative), leaving the entire mantissa availablefor precision.


阅读本文的其余部分以了解更多详细信息。但我怀疑“舍入”(因为我认为您正在使用该术语)对于您的特定应用程序可能不是问题。

关于c++ - 交易时如何防止数字四舍五入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64689685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com