#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
double rand_double() {
return ( ((double)rand())/ ((double)RAND_MAX) );
}
int main(){
double i=rand_double();
double j;
do {
i=(i*0.5);
j=(1+i);
printf("%lf\n", j);
}
while(j>1);
return(0);
}
Asked
Active
Viewed 58 times
-1

Steve Friedl
- 3,929
- 1
- 23
- 30
-
2@KonradRudolph That's not an issue though since `j` is being set before it's ever being read. – Aplet123 Nov 25 '20 at 20:07
-
What surprises you about the final number being `1`? `1 > 1` is false, so the loop stops. – HolyBlackCat Nov 25 '20 at 20:07
-
1As hinted at in the other comment, `1.0000000000001` is greater than `1`. – Adrian Mole Nov 25 '20 at 20:09
-
@Aplet123 Oops, I had read that as `j=(1+j)`. – Konrad Rudolph Nov 25 '20 at 20:12
-
The format for `double` is `"%f"`. If you use `"%lf"`, the `l` is ignored (so it's harmless), but I don't think that was the case in earlier versions of the language. (`long double` uses `"%Lf"`.) – Keith Thompson Nov 25 '20 at 20:13
-
@KeithThompson you're correct, `%lf` has undefined behaviour in C89. – Antti Haapala -- Слава Україні Nov 25 '20 at 20:24
-
If you want to see a variable sequence of pseudo-randoms, then try calling `srand()` once before calling `rand()`. – ryyker Nov 25 '20 at 20:50
-
@ryyker And find out *how* to call `srand()`. One common method is `srand(time(NULL))`. Even so, do not rely on `rand()` to give you high quality random numbers. – Keith Thompson Nov 25 '20 at 21:23
1 Answers
2
The reason is because you are not showing enough decimal places.
So 1.000000
was output where, for example, the value is 1.00000000000000022
which is > 1
.
Please try with more decimal places:
printf("%.17lf\n", j);
The default number of places is typically 6. The double
type is good for about 16-17 significant digits. Revised program output:
1.00062562944425792
1.00031281472212896
1.00015640736106448
1.00007820368053224
1.00003910184026612
1.00001955092013306
1.00000977546006653
1.00000488773003338
1.00000244386501658
1.00000122193250829
1.00000061096625426
1.00000030548312702
1.00000015274156362
1.00000007637078170
1.00000003818539085
1.00000001909269542
1.00000000954634771
1.00000000477317386
1.00000000238658693
1.00000000119329346
1.00000000059664673
1.00000000029832337
1.00000000014916179
1.00000000007458079
1.00000000003729039
1.00000000001864531
1.00000000000932254
1.00000000000466138
1.00000000000233058
1.00000000000116529
1.00000000000058265
1.00000000000029132
1.00000000000014566
1.00000000000007283
1.00000000000003642
1.00000000000001821
1.00000000000000910
1.00000000000000466
1.00000000000000222
1.00000000000000111
1.00000000000000067
1.00000000000000022
1.00000000000000022
1.00000000000000000

Weather Vane
- 33,872
- 7
- 36
- 56