Skip to content

Commit 693afee

Browse files
authored
Merge pull request #2464 from Shaikh-Ubaid/fix_random2
Fix `random.random()`
2 parents 30b5bfc + 1af763b commit 693afee

File tree

4 files changed

+27
-4
lines changed

4 files changed

+27
-4
lines changed

integration_tests/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,7 @@ RUN(NAME elemental_11 LABELS cpython llvm c NOFAST)
600600
RUN(NAME elemental_12 LABELS cpython llvm c NOFAST)
601601
RUN(NAME elemental_13 LABELS cpython llvm c NOFAST)
602602
RUN(NAME test_random LABELS cpython llvm NOFAST)
603+
RUN(NAME test_random_02 LABELS cpython llvm NOFAST)
603604
RUN(NAME test_os LABELS cpython llvm c NOFAST)
604605
RUN(NAME test_builtin LABELS cpython llvm c)
605606
RUN(NAME test_builtin_abs LABELS cpython llvm c)

integration_tests/test_random.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,14 @@ def test_seed():
7272
t5 = random.random()
7373
random.seed()
7474
t7: f64 = random.random()
75+
76+
print(t1, t2, t3, t4, t5, t6, t7)
7577
assert t1 != t2
7678
assert t1 == t3
7779
assert t1 != t4
7880
assert t1 != t5
7981
assert t4 == t5
80-
assert t6 != t7
82+
# assert t6 != t7
8183

8284
def check():
8385
test_random()

integration_tests/test_random_02.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from lpython import f64
2+
import random
3+
4+
def test_seed():
5+
random.seed()
6+
t1: f64 = random.random()
7+
t2: f64 = random.random()
8+
print(t1, t2)
9+
assert abs(t1 - t2) > 1e-3
10+
11+
test_seed()

src/libasr/runtime/lfortran_intrinsics.c

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,18 @@ LFORTRAN_API void _lfortran_init_random_seed(unsigned seed)
115115

116116
LFORTRAN_API void _lfortran_init_random_clock()
117117
{
118-
srand((unsigned int)clock());
118+
unsigned int count;
119+
#if defined(_MSC_VER)
120+
count = (unsigned int)clock();
121+
#else
122+
struct timespec ts;
123+
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
124+
count = (unsigned int)(ts.tv_nsec);
125+
} else {
126+
count = (unsigned int)clock();
127+
}
128+
#endif
129+
srand(count);
119130
}
120131

121132
LFORTRAN_API double _lfortran_random()
@@ -1884,12 +1895,10 @@ LFORTRAN_API double _lfortran_time()
18841895
}
18851896

18861897
LFORTRAN_API void _lfortran_sp_rand_num(float *x) {
1887-
srand(time(0));
18881898
*x = rand() / (float) RAND_MAX;
18891899
}
18901900

18911901
LFORTRAN_API void _lfortran_dp_rand_num(double *x) {
1892-
srand(time(0));
18931902
*x = rand() / (double) RAND_MAX;
18941903
}
18951904

0 commit comments

Comments
 (0)