-2.3 到 3.4 之间有
无穷多的数,比如 -2.30000000000000000000000000000000000000000000000000000000000000000000000000000001
所以你想要的是 -2.3 -2.2 -2.1 …… +3.4 这种间隔为0.1的随机数,
还是 -2.3到+3.4之间间隔尽可能小的随机数?
这两种需求是完全
不一样的。
程序代码:
#include <stdio.h>
#include <stdlib.h>
inline double foo( void )
{
const int a=-23, b=+34;
int r = a + int( (b-a+1)/(1.0+RAND_MAX) * rand() );
return r/10.0;
}
int main( void )
{
unsigned buf[58] = { 0 };
for( int i=0; i<10000; ++i )
{
double v = foo()*10;
int y = int(v>0?v+0.5:v-0.5);
++buf[ y - -23 ];
}
for( int i=0; i!=58; ++i )
printf( "%+.1f %u\n", (i-23)/10.0, buf[i] );
}
输出
-2.3 177
-2.2 163
-2.1 174
-2.0 185
-1.9 166
-1.8 157
-1.7 170
-1.6 154
-1.5 189
-1.4 166
-1.3 180
-1.2 186
-1.1 159
-1.0 167
-0.9 173
-0.8 176
-0.7 156
-0.6 146
-0.5 173
-0.4 172
-0.3 157
-0.2 181
-0.1 170
+0.0 171
+0.1 174
+0.2 161
+0.3 176
+0.4 170
+0.5 172
+0.6 157
+0.7 163
+0.8 182
+0.9 172
+1.0 184
+1.1 172
+1.2 190
+1.3 186
+1.4 198
+1.5 184
+1.6 158
+1.7 159
+1.8 168
+1.9 182
+2.0 176
+2.1 173
+2.2 174
+2.3 166
+2.4 188
+2.5 176
+2.6 177
+2.7 186
+2.8 162
+2.9 166
+3.0 188
+3.1 180
+3.2 170
+3.3 164
+3.4 178
程序代码:
#include <stdio.h>
#include <stdlib.h>
inline double foo( void )
{
const double a=-2.3, b=+3.4;
return a + (b-a)/RAND_MAX * rand();
}
int main( void )
{
unsigned buf[58] = { 0 };
for( int i=0; i<10000; ++i )
{
double v = foo()*10 - -23;
int y = (int)v;
++buf[y];
}
for( int i=0; i!=58; ++i )
printf( "[%+.1f,%+.1f) %u\n", (i-23)/10.0, (i+1-23)/10.0, buf[i] );
}
输出
[-2.3,-2.2) 180
[-2.2,-2.1) 167
[-2.1,-2.0) 180
[-2.0,-1.9) 183
[-1.9,-1.8) 166
[-1.8,-1.7) 164
[-1.7,-1.6) 170
[-1.6,-1.5) 157
[-1.5,-1.4) 193
[-1.4,-1.3) 175
[-1.3,-1.2) 172
[-1.2,-1.1) 201
[-1.1,-1.0) 153
[-1.0,-0.9) 169
[-0.9,-0.8) 181
[-0.8,-0.7) 174
[-0.7,-0.6) 146
[-0.6,-0.5) 165
[-0.5,-0.4) 185
[-0.4,-0.3) 168
[-0.3,-0.2) 161
[-0.2,-0.1) 191
[-0.1,+0.0) 162
[+0.0,+0.1) 176
[+0.1,+0.2) 161
[+0.2,+0.3) 184
[+0.3,+0.4) 176
[+0.4,+0.5) 178
[+0.5,+0.6) 154
[+0.6,+0.7) 177
[+0.7,+0.8) 166
[+0.8,+0.9) 182
[+0.9,+1.0) 183
[+1.0,+1.1) 168
[+1.1,+1.2) 197
[+1.2,+1.3) 200
[+1.3,+1.4) 186
[+1.4,+1.5) 190
[+1.5,+1.6) 175
[+1.6,+1.7) 168
[+1.7,+1.8) 164
[+1.8,+1.9) 178
[+1.9,+2.0) 185
[+2.0,+2.1) 166
[+2.1,+2.2) 196
[+2.2,+2.3) 166
[+2.3,+2.4) 179
[+2.4,+2.5) 176
[+2.5,+2.6) 186
[+2.6,+2.7) 190
[+2.7,+2.8) 167
[+2.8,+2.9) 167
[+2.9,+3.0) 187
[+3.0,+3.1) 187
[+3.1,+3.2) 169
[+3.2,+3.3) 171
[+3.3,+3.4) 182
[+3.4,+3.5) 0