1 //===-- flang/unittests/Runtime/Random.cpp ----------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "flang/Runtime//random.h"
10 #include "gtest/gtest.h"
11 #include "flang/Runtime/descriptor.h"
12 #include "flang/Runtime/type-code.h"
15 using namespace Fortran::runtime
;
17 TEST(RandomNumber
, Real4
) {
18 StaticDescriptor
<1> statDesc
;
19 Descriptor
&harvest
{statDesc
.descriptor()};
20 static constexpr int n
{10000};
22 SubscriptValue extent
[1]{n
};
23 harvest
.Establish(TypeCategory::Real
, 4, xs
, 1, extent
);
24 RTNAME(RandomNumber
)(harvest
, __FILE__
, __LINE__
);
26 for (int j
{0}; j
< n
; ++j
) {
30 std::fprintf(stderr
, "mean of %d random numbers: %g\n", n
, mean
);
31 EXPECT_GE(mean
, 0.95 * 0.5); // mean of uniform dist [0..1] is of course 0.5
32 EXPECT_LE(mean
, 1.05 * 0.5);
34 for (int j
{0}; j
< n
; ++j
) {
35 double diff
{xs
[j
] - mean
};
38 double sdev
{std::sqrt(sumsq
/ n
)};
39 std::fprintf(stderr
, "stddev of %d random numbers: %g\n", n
, sdev
);
40 double expect
{1.0 / std::sqrt(12.0)}; // stddev of uniform dist [0..1]
41 EXPECT_GE(sdev
, 0.95 * expect
);
42 EXPECT_LT(sdev
, 1.05 * expect
);
45 TEST(RandomNumber
, RandomSeed
) {
46 StaticDescriptor
<1> statDesc
[2];
47 Descriptor
&desc
{statDesc
[0].descriptor()};
49 desc
.Establish(TypeCategory::Integer
, 4, &n
, 0, nullptr);
50 RTNAME(RandomSeedSize
)(&desc
, __FILE__
, __LINE__
);
52 SubscriptValue extent
[1]{1};
53 desc
.Establish(TypeCategory::Integer
, 4, &n
, 1, extent
);
54 RTNAME(RandomSeedGet
)(&desc
, __FILE__
, __LINE__
);
55 Descriptor
&harvest
{statDesc
[1].descriptor()};
57 harvest
.Establish(TypeCategory::Real
, 4, &x
, 1, extent
);
58 RTNAME(RandomNumber
)(harvest
, __FILE__
, __LINE__
);
60 RTNAME(RandomSeedPut
)(&desc
, __FILE__
, __LINE__
); // n from RandomSeedGet()
61 RTNAME(RandomNumber
)(harvest
, __FILE__
, __LINE__
);