main.c (2162B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 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 // Note: keep project includes in alphabetical order... 20 #include <stdlib.h> 21 #include <math.h> 22 #include "stdlib/random/base.h" 23 #include "stdlib/random/base/uniform.h" 24 25 /** 26 * Returns a pseudorandom number drawn from a continuous uniform distribution with parameters `a` (minimum support; inclusive) and `b` (maximum support; exclusive). 27 * 28 * ## Notes 29 * 30 * - The function returns `NAN` if provided a `NULL` pointer. 31 * 32 * @param randu PRNG object which generates uniformly distributed pseudorandom numbers on the interval `[0,1)` 33 * @param a minimum support (inclusive) 34 * @param b maximum support (exclusive) 35 * @return pseudorandom number 36 * 37 * @example 38 * #include <stdlib.h> 39 * #include <stdio.h> 40 * #include "stdlib/random/base.h" 41 * #include "stdlib/random/base/randu.h" 42 * #include "stdlib/random/base/uniform.h" 43 * 44 * // Create a PRNG: 45 * struct BasePRNGObject *randu = stdlib_base_random_randu_allocate( 0 ); 46 * if ( randu == NULL ) { 47 * fprintf( stderr, "Error allocating PRNG.\n" ); 48 * exit( 1 ); 49 * } 50 * 51 * double r = stdlib_base_random_uniform( randu, -10.0, 10.0 ); 52 * 53 * // ... 54 * 55 * r = stdlib_base_random_uniform( randu, -10.0, 10.0 ); 56 * 57 * // ... 58 * 59 * r = stdlib_base_random_uniform( randu, -10.0, 10.0 ); 60 * 61 * // ... 62 * 63 * // Free allocated memory: 64 * stdlib_base_random_randu_free( randu, -10.0, 10.0 ); 65 */ 66 double stdlib_base_random_uniform( struct BasePRNGObject *randu, const double a, const double b ) { 67 if ( randu == NULL ) { 68 return NAN; 69 } 70 double r; 71 randu->prng->normalized( randu, &r ); 72 return ( b*r ) + ( (1.0-r)*a ); 73 }