Skip to content

Commit

Permalink
Merge pull request lcompilers#2464 from Shaikh-Ubaid/fix_random2
Browse files Browse the repository at this point in the history
Fix `random.random()`
  • Loading branch information
certik committed Jan 26, 2024
2 parents 30b5bfc + 1af763b commit 693afee
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 4 deletions.
1 change: 1 addition & 0 deletions integration_tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,7 @@ RUN(NAME elemental_11 LABELS cpython llvm c NOFAST)
RUN(NAME elemental_12 LABELS cpython llvm c NOFAST)
RUN(NAME elemental_13 LABELS cpython llvm c NOFAST)
RUN(NAME test_random LABELS cpython llvm NOFAST)
RUN(NAME test_random_02 LABELS cpython llvm NOFAST)
RUN(NAME test_os LABELS cpython llvm c NOFAST)
RUN(NAME test_builtin LABELS cpython llvm c)
RUN(NAME test_builtin_abs LABELS cpython llvm c)
Expand Down
4 changes: 3 additions & 1 deletion integration_tests/test_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,14 @@ def test_seed():
t5 = random.random()
random.seed()
t7: f64 = random.random()

print(t1, t2, t3, t4, t5, t6, t7)
assert t1 != t2
assert t1 == t3
assert t1 != t4
assert t1 != t5
assert t4 == t5
assert t6 != t7
# assert t6 != t7

def check():
test_random()
Expand Down
11 changes: 11 additions & 0 deletions integration_tests/test_random_02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from lpython import f64
import random

def test_seed():
random.seed()
t1: f64 = random.random()
t2: f64 = random.random()
print(t1, t2)
assert abs(t1 - t2) > 1e-3

test_seed()
15 changes: 12 additions & 3 deletions src/libasr/runtime/lfortran_intrinsics.c
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,18 @@ LFORTRAN_API void _lfortran_init_random_seed(unsigned seed)

LFORTRAN_API void _lfortran_init_random_clock()
{
srand((unsigned int)clock());
unsigned int count;
#if defined(_MSC_VER)
count = (unsigned int)clock();
#else
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
count = (unsigned int)(ts.tv_nsec);
} else {
count = (unsigned int)clock();
}
#endif
srand(count);
}

LFORTRAN_API double _lfortran_random()
Expand Down Expand Up @@ -1884,12 +1895,10 @@ LFORTRAN_API double _lfortran_time()
}

LFORTRAN_API void _lfortran_sp_rand_num(float *x) {
srand(time(0));
*x = rand() / (float) RAND_MAX;
}

LFORTRAN_API void _lfortran_dp_rand_num(double *x) {
srand(time(0));
*x = rand() / (double) RAND_MAX;
}

Expand Down

0 comments on commit 693afee

Please sign in to comment.