Parent Directory
|
Revision Log
made 'infty' an acceptable limit of integration for normal function
1 #!/usr/local/bin/webwork-perl 2 3 =head1 Statistics Macros 4 5 =head3 Normal distribution 6 7 =pod 8 9 Usage: normal(a, b, mean=>0, deviation=>1); 10 11 Computes the probability of x being in the interval (a,b) for normal distribution. 12 The first two arguments are required. Use '-infty' for negative infinity, and 'infty' or '+infty' for positive infinity. 13 The mean and deviation are optional, and are 0 and 1 respectively by default. 14 15 =cut 16 17 sub normal { 18 my $a = shift; 19 my $b = shift; 20 my %options = @_; 21 my $mean = $options{'mean'} if defined ($options{'mean'}); 22 $mean = 0 unless defined $mean; 23 my $deviation = $options{'deviation'} if defined ($options{'deviation'}); 24 $deviation = 1 unless defined $deviation; 25 if ($deviation <= 0) { 26 warn 'Deviation must be a positive number.'; 27 return; 28 } 29 if ( $a eq '-infty' ) { $a = -6*$deviation + $mean; } 30 if ( $b eq 'infty' ) { $b = 6*$deviation + $mean; } 31 if ( $b eq '+infty' ) { $b = 6*$deviation + $mean; } 32 my $z_score_of_a = ($a - $mean)/$deviation; 33 my $z_score_of_b = ($b - $mean)/$deviation; 34 my $function = sub { my $x=shift; 35 $E**(-$x**2/2)/sqrt(2*$PI); 36 }; 37 my $prob = romberg($function, $z_score_of_a, $z_score_of_b); 38 $prob; 39 } 40 41 =head3 "Inverse" of normal distribution 42 43 =pod 44 45 Usage: inv_normal(prob, mean=>0, deviation=>1); 46 47 Computes the positive number b such that the probability of x being in the interval (0,b) 48 is equal to the given probability (first argument). The mean and deviation are 49 optional, and are 0 and 1 respectively by default. 50 Caution: since students may use tables, they may only be able to provide the answer correct to 2 or 3 51 decimal places. Use tolerance when evaluating answers. 52 53 =cut 54 55 sub inv_normal { 56 my $prob = shift; 57 my %options = @_; 58 my $mean = $options{'mean'} if defined ($options{'mean'}); 59 $mean = 0 unless defined $mean; 60 my $deviation = $options{'deviation'} if defined ($options{'deviation'}); 61 $deviation = 1 unless defined $deviation; 62 if ($deviation <= 0) { 63 warn 'Deviation must be a positive number.'; 64 return; 65 } 66 my $function = sub { my $x=shift; 67 $E**(-$x**2/2)/sqrt(2*$PI); 68 }; 69 my $z_score_of_b = inv_romberg($function, 0, $prob); 70 my $b = $z_score_of_b * $deviation + $mean; 71 $b; 72 } 73 74 ########################################## 75 76 1;
| aubreyja at gmail dot com | ViewVC Help |
| Powered by ViewVC 1.0.9 |