接 https://blog.csdn.net/qq_40893824/article/details/105907220 中的 1.4.3
1 代码
#include<bits/stdc++.h>
#define min 1e-4
using namespace std;
long long LLmyrand(long long length)
{
long long r, p;
if(length < 32768)
return rand()%(length+1);
else
{
r = rand();
p = (1.0*r/32767)*length;
//cout << "粗略 p - m = " << p << endl;
if (r < 32767)
{
length = (1.0*(r + 1)/32767)*length - (1.0*r/32767)*length;
p += LLmyrand(length);
}
return p;
}
}
long double LDmyrand(long double length)
{
long long r;
long double p, leng;
r = LLmyrand((long long)length);
//cout << "粗略 p - m = " << p << endl;
p = (long double)r ;
leng = length - r;
if(leng >= 1)
{
p += (1.0*rand())/32768;
}
else
{
p += (1.0*rand())/32767*leng;
}
return p;
}
void creat()
{
long long m, n, p, i, length;
long double m1, n1, p1, length1;
cout << "n - m > 32768 生成整数 - 改进" << endl << endl;
m = -2111231231231;
n = 33112312312312;
cout << "m = " << m << endl;
cout << "n = " << n << endl;
cout << "在[" << m << ", " << n << "]中随机取整数:" << endl << endl;
for(i = 0; i < 10; i++)
{
length = n - m;
p = LLmyrand(length) + m;
//cout << "p - m = " << p - m << endl;
cout << "第" << setw(2) << i + 1 << " 次:p = " << p << endl << endl;
}
cout << endl << endl << endl;
cout << "n1 - m1 > 32768 生成浮点数 - 改进" << endl << endl;
m1 = -1231123123.123123123;
n1 = 1231123123.1212;
cout << "m1 = " << setprecision(20) << m1 << endl;
cout << "n1 = " << setprecision(20) << n1 << endl;
cout << "在[" << setprecision(20) << m1 << ", " << n1 << "]中随机取浮点数:" << endl << endl;
for(i = 0; i < 10; i++)
{
length1 = n1 - m1;
p1 = LDmyrand(length1) + m1;
//cout << "p1 - m1 = " << p1 - m1 << endl;
cout << "第" << setw(2) << i + 1 << " 次:p1 = " << setprecision(20) <<p1 << endl << endl;
}
cout << endl << endl << endl;
}
int main()
{
srand(time(NULL));
int i;
i = rand();
creat();
system("pause");
return 0;
}
2 运行情况