Source : https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-2
Objective
In this challenge, we practice solving problems based on the Central Limit Theorem. We recommend reviewing the Central Limit Theorem Tutorial before attempting this challenge.
Task
The number of tickets purchased by each student for the University X vs. University Y football game follows a distribution that has a mean of and a standard deviation of .
A few hours before the game starts, eager students line up to purchase last-minute tickets. If there are only tickets left, what is the probability that all students will be able to purchase tickets?
Input Format
There are lines of input (shown below):
250
100
2.4
2.0
The first line contains the number of last-minute tickets available at the box office. The second line contains the number of students waiting to buy tickets. The third line contains the mean number of purchased tickets, and the fourth line contains the standard deviation.
If you do not wish to read this information from stdin, you can hard-code it into your program.
Output Format
Print the probability that students can successfully purchase the remaining tickets, rounded to a scale of decimal places (i.e., format).
Source : https://www.hackerrank.com/challenges/s10-the-central-limit-theorem-2
Solution
// Karthikalapati.blogspot.com | |
public class Solution { | |
public static void main(String[] args) { | |
double ticketsLeft = 250; | |
int n = 100; | |
double mean = 2.4; | |
double std = 2; | |
/* Formulas are from problem's tutorial */ | |
double samplesMean = n * mean; | |
double samplesSTD = Math.sqrt(n) * std; | |
System.out.format("%.4f", cumulative(samplesMean, samplesSTD, ticketsLeft)); | |
} | |
/* Calculates cumulative probability */ | |
public static double cumulative(double mean, double std, double x) { | |
double parameter = (x - mean) / (std * Math.sqrt(2)); | |
return (0.5) * (1 + erf(parameter)); | |
} | |
/* Source: http://introcs.cs.princeton.edu/java/21function/ErrorFunction.java.html */ | |
// fractional error in math formula less than 1.2 * 10 ^ -7. | |
// although subject to catastrophic cancellation when z in very close to 0 | |
// from Chebyshev fitting formula for erf(z) from Numerical Recipes, 6.2 | |
public static double erf(double z) { | |
double t = 1.0 / (1.0 + 0.5 * Math.abs(z)); | |
// use Horner's method | |
double ans = 1 - t * Math.exp( -z*z - 1.26551223 + | |
t * ( 1.00002368 + | |
t * ( 0.37409196 + | |
t * ( 0.09678418 + | |
t * (-0.18628806 + | |
t * ( 0.27886807 + | |
t * (-1.13520398 + | |
t * ( 1.48851587 + | |
t * (-0.82215223 + | |
t * ( 0.17087277)))))))))); | |
if (z >= 0) return ans; | |
else return -ans; | |
} | |
} |
No comments:
Post a Comment