本文主要是介绍随机数 -- 线性同余,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include<iostream>
#include<iomanip>
#include<stdlib.h>
#include<math.h>
using namespace std;const int sizes = 100;double random( int& temp ){int i;int result;static int x1,x2,x3;static int iff;static double ran[sizes];double rm1 = 0.0000038580247;double rm2 = 0.0000074373773;int m1 = 259200;int m2 = 134456;int m3 = 243000;int a1 = 7141;int a2 = 8121;int a3 = 4561;int c1 = 54773;int c2 = 28411;int c3 = 51349;if( ( temp < 0 ) || ( iff == 0 ) ){iff = 1;x1 = ( c1 - temp ) % m1;x1 = ( x1 * a1 + c1 ) % m1;x2 = x1 % m2;x1 = ( x1 * a1 + c1 ) % m1;x3 = x1 % m3;for( i = 1; i < sizes; ++i ){x1 = ( a1 * x1 + c1 ) % m1;x2 = ( a2 * x2 + c2 ) % m2;ran[i] = ( double( x1 ) + double( x2 ) * rm2 ) * rm1;}temp = 1;}x1 = ( x1 * a1 + c1 ) % m1;x2 = ( x2 * a2 + c2 ) % m2;x3 = ( x3 * a3 + c3 ) % m3;i = 1 + int( ( ( sizes - 1 ) * x3 ) / m3 );if( ( i > sizes - 1 ) || ( i < 1 ) ){cout << "abnormal exit." << endl;return 1;}result = ran[i];ran[i] = ( float( x1 ) + float( x2 ) * rm2 ) * rm1;return result;
}double function( double x1, double x2, double x3, double x4 ){double t = sqrt( x1 * x1 + x2 * x2 + x3 * x3 + x4 * x4);return t;
}void main(){double yprob[4], a, b, pi, x1, x2, x3, x4, k;int iy[4], temp, j, i, m;temp = -1;pi = 3.1415926;a = 0.0;b = 0.0;for( i = 0; i <= 3; ++i )iy[i] = 0;cout << "Volume of nuit n-sphere,n=2,3,4" << endl;cout << "# points pi [4/3]*pi [1/2]*pi^2" << endl;for( j = 1; j <= 15; ++j ){for( k = pow( 2, ( j - 1 ) ); k <= pow( 2, j ); ++k ){x1 = random( temp );x2 = random( temp );x3 = random( temp );x4 = random( temp );if( function( x1, x2, a, b ) < 1.0 )iy[1] = iy[1] + 1;if( function( x1, x2, x3, a) < 1.0 )iy[2] = iy[2] + 1;if( function( x1, x2, x3, x4) < 1.0 ) iy[3] = iy[3] + 1;}for( i = 1; i <= 3; i++ )yprob[i] = 1.0 * pow( 2, ( i + 1 ) ) * iy[i] / pow( 2, j );cout << setprecision( 0 ) << setiosflags( ios::fixed ) << setw( 8 ) << pow( 2, j );for( m = 1; m <= 3; ++m )cout << setprecision( 6 ) << setiosflags( ios::fixed ) << setw( 14 ) << yprob[m];cout << endl;}cout << setprecision( 6 ) << setiosflags( ios::fixed ) << setw( 8 ) << "actual" << pi;cout << setprecision( 6 ) << setiosflags( ios::fixed ) << setw( 14 ) << 4.0 * pi / 3.0;cout << setprecision( 6 ) << setiosflags( ios::fixed ) << setw( 14 ) << 0.5 * pow( pi, 2 ) << endl;return 0;}
这篇关于随机数 -- 线性同余的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!