Skip to content

Commit d7fb715

Browse files
committed
feat: add random/tools/unary
--- type: pre_commit_static_analysis_report description: Results of running static analysis checks when committing changes. report: - task: lint_filenames status: passed - task: lint_editorconfig status: passed - task: lint_markdown status: passed - task: lint_package_json status: passed - task: lint_repl_help status: na - task: lint_javascript_src status: passed - task: lint_javascript_cli status: na - task: lint_javascript_examples status: passed - task: lint_javascript_tests status: passed - task: lint_javascript_benchmarks status: passed - task: lint_python status: na - task: lint_r status: na - task: lint_c_src status: na - task: lint_c_examples status: na - task: lint_c_benchmarks status: na - task: lint_c_tests_fixtures status: na - task: lint_shell status: na - task: lint_typescript_declarations status: na - task: lint_typescript_tests status: na - task: lint_license_headers status: passed ---
1 parent ed1b563 commit d7fb715

File tree

11 files changed

+1492
-0
lines changed

11 files changed

+1492
-0
lines changed
Lines changed: 271 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2025 The Stdlib Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
19+
-->
20+
21+
# Random
22+
23+
> Constructor for creating ndarrays filled with pseudorandom numbers drawn from a single-parameter probability distribution.
24+
25+
<!-- Section to include introductory text. Make sure to keep an empty line after the intro `section` element and another before the `/section` close. -->
26+
27+
<section class="intro">
28+
29+
</section>
30+
31+
<!-- /.intro -->
32+
33+
<!-- Package usage documentation. -->
34+
35+
<section class="usage">
36+
37+
## Usage
38+
39+
```javascript
40+
var Random = require( '@stdlib/random/tools/unary' );
41+
```
42+
43+
#### Random( prng, idtypes odtypes, policies\[, options] )
44+
45+
Returns an interface for creating ndarrays filled with pseudorandom numbers drawn from a single-parameter probability distribution.
46+
47+
```javascript
48+
var dtypes = require( '@stdlib/ndarray/dtypes' );
49+
var exponential = require( '@stdlib/random/base/exponential' );
50+
51+
var idt = dtypes( 'real_and_generic' );
52+
var odt = dtypes( 'real_floating_point_and_generic' );
53+
54+
var policies = {
55+
'output': 'real_floating_point_and_generic'
56+
};
57+
var options = {
58+
'order': 'row-major'
59+
};
60+
61+
var rand = new Random( exponential, idt, odt, policies, options );
62+
```
63+
64+
The constructor has the following parameters:
65+
66+
- **prng**: unary pseudorandom number generator.
67+
68+
- **idtypes**: list of supported input data types.
69+
70+
- **odtypes**: list of supported output data types.
71+
72+
- **policies**: interface policies. Must have the following properties:
73+
74+
- **output**: output data type [policy][@stdlib/ndarray/policies].
75+
76+
- **options**: function options (_optional_).
77+
78+
The constructor supports the following options:
79+
80+
- **order**: default memory layout [order][@stdlib/ndarray/orders].
81+
82+
#### Random.prototype.generate( shape, param1\[, options] )
83+
84+
Returns an ndarray filled with pseudorandom numbers drawn from a probability distribution.
85+
86+
```javascript
87+
var dtypes = require( '@stdlib/ndarray/dtypes' );
88+
var exponential = require( '@stdlib/random/base/exponential' );
89+
90+
var idt = dtypes( 'real_and_generic' );
91+
var odt = dtypes( 'real_floating_point_and_generic' );
92+
93+
var policies = {
94+
'output': 'real_floating_point_and_generic'
95+
};
96+
var options = {
97+
'order': 'row-major'
98+
};
99+
100+
var rand = new Random( exponential, idt, odt, policies, options );
101+
102+
var v = rand.generate( [ 2, 2 ], 2.0 );
103+
// returns <ndarray>
104+
```
105+
106+
The method has the following parameters:
107+
108+
- **shape**: output ndarray shape.
109+
- **param1**: distribution parameter. May be either a scalar or an ndarray. If an ndarray, must be [broadcast compatible][@stdlib/ndarray/base/broadcast-shapes] with the specified output ndarray shape.
110+
- **options**: function options (_optional_).
111+
112+
The method accepts the following options:
113+
114+
- **dtype**: output ndarray data type. Setting this option overrides the output data type policy.
115+
- **order**: memory layout. Setting this option overrides the default memory layout order.
116+
- **mode**: specifies how to handle indices which exceed ndarray dimensions.
117+
- **submode**: specifies how to handle subscripts which exceed ndarray dimensions on a per dimension basis.
118+
- **readonly**: boolean indicating whether an ndarray should be read-only.
119+
120+
By default, the method returns an ndarray having a data type determined by the output data type policy. To override the default behavior, set the `dtype` option.
121+
122+
```javascript
123+
var dtypes = require( '@stdlib/ndarray/dtypes' );
124+
var getDType = require( '@stdlib/ndarray/dtype' );
125+
var exponential = require( '@stdlib/random/base/exponential' );
126+
127+
var idt = dtypes( 'real_and_generic' );
128+
var odt = dtypes( 'real_floating_point_and_generic' );
129+
130+
var policies = {
131+
'output': 'real_floating_point_and_generic'
132+
};
133+
var options = {
134+
'order': 'row-major'
135+
};
136+
137+
var rand = new Random( exponential, idt, odt, policies, options );
138+
139+
var v = rand.generate( [ 2, 2 ], 2.0, {
140+
'dtype': 'generic'
141+
});
142+
// returns <ndarray>
143+
144+
var dt = getDType( v );
145+
// returns 'generic'
146+
```
147+
148+
#### Random.prototype.assign( param1, out )
149+
150+
Fills an ndarray with pseudorandom numbers drawn from a probability distribution.
151+
152+
```javascript
153+
var dtypes = require( '@stdlib/ndarray/dtypes' );
154+
var ndzeros = require( '@stdlib/ndarray/zeros' );
155+
var exponential = require( '@stdlib/random/base/exponential' );
156+
157+
var idt = dtypes( 'real_and_generic' );
158+
var odt = dtypes( 'real_floating_point_and_generic' );
159+
160+
var policies = {
161+
'output': 'real_floating_point_and_generic'
162+
};
163+
var options = {
164+
'order': 'row-major'
165+
};
166+
167+
var rand = new Random( exponential, idt, odt, policies, options );
168+
169+
var out = ndzeros( [ 2, 2 ] );
170+
var v = rand.assign( 2.0, out );
171+
// returns <ndarray>
172+
173+
var bool = ( v === out );
174+
// returns true
175+
```
176+
177+
The method has the following parameters:
178+
179+
- **param1**: distribution parameter. May be either a scalar or an ndarray. If an ndarray, must be [broadcast compatible][@stdlib/ndarray/base/broadcast-shapes] with the output ndarray.
180+
- **out**: output ndarray.
181+
182+
</section>
183+
184+
<!-- /.usage -->
185+
186+
<!-- Package usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
187+
188+
<section class="notes">
189+
190+
## Notes
191+
192+
- The output data type policy only applies to the `generate` method. For the `assign` method, the output ndarray is allowed to have any supported output data type.
193+
194+
</section>
195+
196+
<!-- /.notes -->
197+
198+
<!-- Package usage examples. -->
199+
200+
<section class="examples">
201+
202+
## Examples
203+
204+
<!-- eslint no-undef: "error" -->
205+
206+
```javascript
207+
var exponential = require( '@stdlib/random/base/exponential' );
208+
var dtypes = require( '@stdlib/ndarray/dtypes' );
209+
var ndarray = require( '@stdlib/ndarray/ctor' );
210+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
211+
var Random = require( '@stdlib/random/tools/unary' );
212+
213+
// Create a new PRNG instance...
214+
var idt = dtypes( 'real_and_generic' );
215+
var odt = dtypes( 'real_floating_point_and_generic' );
216+
var policies = {
217+
'output': 'real_floating_point_and_generic'
218+
};
219+
var random = new Random( exponential, idt, odt, policies );
220+
221+
// Generate a 3x3 matrix of pseudorandom numbers:
222+
var x = random.generate( [ 3, 3 ], 2.0 );
223+
console.log( ndarray2array( x ) );
224+
225+
// Generate another matrix with a specified data type:
226+
x = random.generate( [ 3, 3 ], 2.0, {
227+
'dtype': 'float32'
228+
});
229+
console.log( ndarray2array( x ) );
230+
231+
// Define an array of distribution parameters:
232+
var param = new ndarray( 'generic', [ 2.0, 20.0, 200.0 ], [ 3, 1 ], [ 1, 1 ], 0, 'row-major' );
233+
234+
// Broadcast the parameters to generate another 3x3 matrix of pseudorandom numbers:
235+
x = random.generate( [ 3, 3 ], param );
236+
console.log( ndarray2array( x ) );
237+
```
238+
239+
</section>
240+
241+
<!-- /.examples -->
242+
243+
<!-- Section to include cited references. If references are included, add a horizontal rule *before* the section. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
244+
245+
<section class="references">
246+
247+
</section>
248+
249+
<!-- /.references -->
250+
251+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
252+
253+
<section class="related">
254+
255+
</section>
256+
257+
<!-- /.related -->
258+
259+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
260+
261+
<section class="links">
262+
263+
[@stdlib/ndarray/policies]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/policies
264+
265+
[@stdlib/ndarray/orders]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/orders
266+
267+
[@stdlib/ndarray/base/broadcast-shapes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/base/broadcast-shapes
268+
269+
</section>
270+
271+
<!-- /.links -->
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2025 The Stdlib Authors.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
'use strict';
20+
21+
// MODULES //
22+
23+
var bench = require( '@stdlib/bench' );
24+
var isnan = require( '@stdlib/math/base/assert/is-nan' );
25+
var pow = require( '@stdlib/math/base/special/pow' );
26+
var dtypes = require( '@stdlib/ndarray/dtypes' );
27+
var exponential = require( '@stdlib/random/base/exponential' );
28+
var zeros = require( '@stdlib/ndarray/zeros' );
29+
var pkg = require( './../package.json' ).name;
30+
var Random = require( './../lib' );
31+
32+
33+
// FUNCTIONS //
34+
35+
/**
36+
* Creates a benchmark function.
37+
*
38+
* @private
39+
* @param {PositiveInteger} len - array length
40+
* @returns {Function} benchmark function
41+
*/
42+
function createBenchmark( len ) {
43+
var policies;
44+
var random;
45+
var out;
46+
var dt;
47+
48+
dt = dtypes( 'real_floating_point' );
49+
policies = {
50+
'output': 'same',
51+
'casting': 'none'
52+
};
53+
random = new Random( exponential, dt, dt, policies );
54+
55+
out = zeros( [ len ] );
56+
57+
return benchmark;
58+
59+
/**
60+
* Benchmark function.
61+
*
62+
* @private
63+
* @param {Benchmark} b - benchmark instance
64+
*/
65+
function benchmark( b ) {
66+
var o;
67+
var i;
68+
69+
b.tic();
70+
for ( i = 0; i < b.iterations; i++ ) {
71+
o = random.assign( 2.0, out );
72+
if ( typeof o !== 'object' ) {
73+
b.fail( 'should return an ndarray' );
74+
}
75+
}
76+
b.toc();
77+
if ( isnan( o.get( i%len ) ) ) {
78+
b.fail( 'should not return NaN' );
79+
}
80+
b.pass( 'benchmark finished' );
81+
b.end();
82+
}
83+
}
84+
85+
86+
// MAIN //
87+
88+
/**
89+
* Main execution sequence.
90+
*
91+
* @private
92+
*/
93+
function main() {
94+
var len;
95+
var min;
96+
var max;
97+
var f;
98+
var i;
99+
100+
min = 1; // 10^min
101+
max = 6; // 10^max
102+
103+
for ( i = min; i <= max; i++ ) {
104+
len = pow( 10, i );
105+
f = createBenchmark( len );
106+
bench( pkg+':assign:len='+len, f );
107+
}
108+
}
109+
110+
main();

0 commit comments

Comments
 (0)