Statistical method - java

So in my code, it seems that in the fillRandomArray method, instead of getting an array of 100 random numbers, I just get straight zeros and I don't know how to fix it. It seems to me that the problem has to do with the first for loop, or potentially the declaration of the double array in the public class statistical model.
import javax.swing.*;
import java.util.*;
import java.util.Arrays;
public class statisticalModel {
//Initates a place for the normal curve to be placed.
static double Ho;
//Real proportion of data statistic.
static double Ha;
//Estimated real proportion of data statistic.
static int Pop;
//Population size.
static int Zscore;
//Z score, or the amount of standard deviations away from the mean.
//Z score = sqrt(P(1-p)/N)
static double stdDev;
//Standard Deviation, follows the 65, 95, 99 model. 65 percent of all scores
//fall in one standard deviation of the mean. 95 percent of all scores fall
//within two standard deviations of the mean. 99 percent of all scores fall
//within three standard deviations of the mean.
static double mean;
//The average of all the scores of the array.
static double variance;
//The average difference between sets of values within the array.
static double[] meanScores = new double[100];
//Array meant to generate a set of random values within the normal curve of
//the model, following the 65, 95, 99 rule.
static String desiredValue = "";
//This is a string set to the user's command. Tells whether or not the value should
//be lower than, higher than, or not equal to Ho.
static Scanner sc = new Scanner(System.in);
//Scanner to take in values listed above.
static int size = 100;
//Variable that measures the size of the array.
static int temporary;
//Value Holder for For Loops, While Loops, If Statements, etc.
static double pValue;
//P Value which represents how far a statistic deviates from the expected mean of a population.
public static void main(String args[])
{
runStatisticalMethod();
}
public static void runStatisticalMethod()
{
takeInData();
calculateStats();
System.out.println(Arrays.toString(meanScores));
explainSolution();
}
public static void takeInData()
{
System.out.println("Please enter your desired Ho");
Ho = sc.nextDouble();
System.out.println("Please enter your desired Ha");
Ha = sc.nextDouble();
System.out.println("Please enter your desired population size");
Pop = sc.nextInt();
System.out.println("Thanks for entering your data. Your data will be compiled below");
}
//Fills the array meanScores with random integers.
public static void fillRandomArray()
{
for (int z = 0; z < 100; z++) {
meanScores[z] = (Math.random() * 100) + (stdDev * 3);
}
assignStdDev();
for (int x = 0; x < 99; x++) {
for (int y = 0; y < 99; y++) {
if (meanScores[y] >= meanScores[y + 1]) {
double valueHolder1 = meanScores[y];
double valueHolder2 = meanScores[y + 1];
meanScores[y + 1] = valueHolder1;
meanScores[y] = valueHolder2;
}
}
}
}
public static void assignStdDev()
{
for (int x = 5; x >= 5 && x <= 95; x++) {
meanScores[x] -= (stdDev * Math.random());
}
for (int x = 31; x >= 31 && x < 66; x++) {
meanScores[x] -= (stdDev * Math.random());
}
}
//Calculates a set of statistics including standard deviation, z-score, mean,
//interquartile range, probability, and variance.
public static void calculateStats()
{
//Calculates the Mean of the inputted variables and normal curve.
int sum = 0;
for (int a = 0; a < 100; a++) {
sum += a;
}
mean = sum / size;
//Calculate the Variance of the inputted variables and normal curve.
for (int b = 0; b < 100; b++) {
temporary += (b - mean) * (b - mean);
}
variance = temporary / size;
//Calculate the Standard Deviation of the inputted variables and normal curve.
stdDev = Math.sqrt(variance);
//Calculate the P-Value and use the p value to determine whether or not the hypothesis is valid.
pValue = (Ha - Ho) / (stdDev / Math.sqrt(Pop));
}
//This method explains the numbers generated in terms of statistics and analyzes
//if the hypothesis is probably. If not, a possible solution is proposed with
//regards to what should be changed. Also explains the curve of the graph.
public static void explainSolution()
{
if (Math.abs(pValue) < .05) {
System.out.println(
"Based on the information you have given me, the hypothesis test seems to show information that your Ha is possibly correct, thus failing to reject your hypothesis");
} else if (Math.abs(pValue) > .05) {
System.out.println(
"Based on the information you have given me, the hypothesis test seems to lack information to show that your Ha is possibly correct, thus rejecting your hypothesis");
}
}
}

Related

math.sqrt gives me incorrect result (double)

I am writing a program that prints 100 random coordinates within a circle. The circle has the radius 10 and its center is located at (0,0). However, some of the coordinates y:value is incorrectly calculated when I'm using: y = Math.sqrt(100 -x^2) The result is like off... Why is that ? (See picture) For positive y:values, they get too big sometimes and its because of the math.sqrt calculation with doubles.
package RKap14;
import ZindansMethods.ZindanRandom;
public class Dot {
public double x;
public double y;
public static void main(String[] arg)throws Exception {
//Create the array with null fields?
Coord[] c;
//Decide how many fields
c = new Coord[100];
//Create an object of class Coord in each slot of the array
for(int i = 0; i<c.length; i++) {
c[i] = new Coord();
}
//Assign random coordinates for each field x & y
for(int i = 0; i<c.length; i++) {
c[i].x = ZindanRandom.randomized(-10,10);
//Since sometimes Java calculates wrong and gives numbers above 10 and below -10...
while(c[i].x > 10 || c[i].x < -10)
c[i].x = ZindanRandom.randomized(-10,10);
c[i].y = ZindanRandom.randomized(-Math.sqrt(100-c[i].x*c[i].x), Math.sqrt(100-c[i].x*c[i].x));
}
//Print out the coordinates in form: (x,y),(x1,y1)...(x99,y99)
for (int i = 0; i<c.length; i++) {
System.out.print("(" + c[i].x + "," + c[i].y + ")" + ",");
}
}
}
class Coord {
double x;
double y;
}
The random method I am using:
//Gives random number a to b. For example -10 <= x <= 10
public static double randomized (double a, double b) {
return (a-1+Math.random()*Math.abs(b-a+1)+1);
}
I don't know what to try. I tried doing this program with a trigonometric approach but I'd rather understand why the calculator is doing its job wrongfully. Are there too many decimals? Can I do something about it ?
Circle test
your random function is generating numbers outside the given range
for example if you substitute the values into your equation and and use 1 as the value returned from Math.random() you will get 101.
Try the following random function instead:
public static double randomized(double min, double max)
return Math.random() * (max - min) + min;
}

My code doesn't calculate min and max numbers

I'm trying to write a code which will show the highest, lowest, the difference of them and the average of inputted 30 numbers.
But its not working and is showing the same result for both min and max numbers. Here is the code.
public class aa {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] daystemp = new int[30];
int i = 0;
int dayHot = 0;
int dayCold = 0;
while(i < daystemp.length){
daystemp[i] = input.nextInt();
i++;
}
int maxTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] > maxTemp) {
maxTemp = daystemp[i];
dayHot = i + 1;
i++;
}
}
System.out.println(maxTemp);
int minTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] < minTemp) {
minTemp = daystemp[i];
dayCold = i + 1;
i++;
}
}
System.out.println(minTemp);
int diff = maxTemp - minTemp;
System.out.println("The difference between them is"+diff);
double sum = 0;
while(i < daystemp.length) {
sum += daystemp[i];
i++;
}
double average = sum / daystemp.length;
System.out.println("Average was"+average);
}
}
After the first loop (the input loop), i value is daystemp.length (i.e. 30).
It's never reset to 0. So each while loop condition is false.
Add i=0 before the loops and do i++outside the ifblocks or your code will never end.
example:
i=0;
int maxTemp = daystemp[0];
while (i < daystemp.length) {
if (daystemp[i] > maxTemp) {
maxTemp = daystemp[i];
dayHot = i + 1;
}
i++;
}
A few notes about this solution:
By declaring the cumulative total double, no casting is required.
Because Java knows you want to convert int to double automatically if you assign an int to a declared double. Similary the fact that you want to express a result as double is implied when dividing a double by an int, such as when the average is taken. That avoids a cast also. If you had two ints and you wanted to produce a double you'd need to cast one or more of them, or in cases like a print statement where the compiler can't deduce the optimal type for the parameter, you'd need to explicitly cast to covert an int value to a double.
Not sure what OS you're running this on. The ideal situation would be to make it work on all platforms without requiring people type a magic word to end input (because how tacky). The easiest way to end input is to use the OS-specific end of input (end of file) key combination, and for Linux it's CTRL/D, which is how I explained it in the prompt. On another OS with a different end of input sequence you could just change the prompt. The trickiest would be if it is supposed to be truly portable Java. In that case I'd personally investigate how I could figure out the OS and/or End of File character or key combination on the current OS and modify the prompt to indicate to end input with whatever that is. That would be a bit of and advanced assignment but a very cool result.
Example illustrates use of a named constant to determine the array and is used limit the amount of input (and could be used to limit loop count of for loops accessing the array).
By setting the min and max to very high and low values respectively (notice the LOW value assigned to max and HIGH value assigned to min, those ensure the first legit temp entered will set the min and max and things will go from there).
Temperature Maximum, Minimum, Average and Difference Calculator
import java.util.Scanner;
public class TemperatureStats {
final static int MAX_DAYS = 31;
public static void main(String[] args) {
int[] dayTemps = new int[MAX_DAYS];
double cumulativeTemp = 0.0;
int minTemp = 1000, maxTemp = -1000;
Scanner input = new Scanner(System.in);
System.out.println("Enter temps for up to 1 month of days (end with CTRL/D):");
int entryCount = 0;
while (input.hasNextInt() && entryCount < MAX_DAYS)
dayTemps[entryCount++] = input.nextInt();
/* Find min, max, cumulative total */
for (int i = 0; i < entryCount; i++) {
int temp = dayTemps[i];
if (temp < minTemp)
minTemp = temp;
if (temp > maxTemp)
maxTemp = temp;
cumulativeTemp += temp;
}
System.out.println("High temp. = " + maxTemp);
System.out.println("Low temp. = " + minTemp);
System.out.println("Difference = " + (maxTemp - minTemp));
System.out.println("Avg temp. = " + cumulativeTemp / entryCount);
}
}

The question is around the "Gambling" zone with addition of math

after adding two int variables to (a) and (b),
I have to gamble (a) times values between 10 to 100 and
calculate which square root of these gambled numbers is the closest to (b).
For example a=3 and b=2
output:
Gambled 16,25,49.
The number 16 was chosen since it's square root (4) is the closest to b=2.
I am stuck in the part of calculation of the square root, and saving the closest value to b each time the loop runs, i'm not allowed to use arrays,
this is the third question of my first task and i'd appreciate any experienced ideas to be shared ^^.
(MyConsole is a replacement for the scan command)
int a = MyConsole.readInt("Enter value a:");
int b = MyConsole.readInt("Enter value b:");
for(int i = 0; i<a; a--){
int gambler = ((int)(Math.random() *91)+10);
double Root = Math.sqrt(gambler);
double Distance= Root-b;
{
System.out.println();
Here is how I found the minimum. You can also use arrays to store all the gambling values if you want for future use. I also used Scanner but you can use your MyConsole I'm just not familiar with it. I hope it helps. דש מישראל
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter value a:");
int a = scanner.nextInt();
System.out.println("Enter value b:");
int b = scanner.nextInt();
double min = 100;
for (int i = 0; i < a; i++) {
int gambler = ((int) (Math.random() * 91) + 10);
double root = Math.sqrt(gambler);
double distance = Math.abs(root - b);
if (min > distance)
min = distance;
}
System.out.println("minimum value is: " + min);
}

How do I change Procedural Programming into OOP..? (JAVA)

I am a beginner Java programmer and have toiled over this for quite some time. I need to convert the program below into OOP format and cannot get it to compile without error. I figured I would post the working non-formatted program rather than my failed and choppy attempts. If anyone could convert the below program into OOP, it would be very much appreciated. Please forgive any inefficiencies or sloppiness as I am new to this.
Thanks for helping :)
import java.util.Scanner;
public class EstimatePi
{
//Public static variables used because they are used throughout the different methods
public static Scanner in = new Scanner(System.in);
//2 * Math.random - 1 is used to guarentee that the max value is gonna be 1 and min is gonna be -1
public static double x = (2 * Math.random() - 1);
public static double y = (2 * Math.random() - 1);
public static double radius = 1.0;
public static double numOnBoard;
public static double totalPi;
public static int numThrows;
public static int trials;
public static int hits(double x, double y, int trials) {
numOnBoard = 0;
for (int i = 1; i < trials; i++) {
//Same Algorithm as above
x = (2 * Math.random() - 1);
y = (2 * Math.random() - 1);
//If x2 + y2 <= r2 then its a hit on the board.
if ((Math.pow(x, 2) + Math.pow(y, 2)) <= (Math.pow(radius, 2))) {
numOnBoard++;
}
}
//returns the num of hits on the board
return (int)numOnBoard;
}
//Method to calculate pi, and store that data in an array
public static double[] piColumn( double numOnBoard, double numThrows)
{ double []piColumn = new double[trials];
for(int i = 0; i < piColumn.length;i++)
{
//Formula to calculate the pi
piColumn[i] = (4 * (numOnBoard) / numThrows);
}
return piColumn;
}
public static void main (String [ ] args)
{
//The number of darts thrown per trial is asked
System.out.println("How many times should the dart be thrown per trial?");
numThrows = in.nextInt();
System.out.println();
//The number of trials is asked
System.out.println("How many trials do you want to simulate?");
trials = in.nextInt();
System.out.println();
//forloop to iterate the internal code while counter < trials
for (int counter = 0; counter < trials; counter++) {
//number of hits methods is declared as a integer
int hits = hits(x,y,numThrows);
//the calculation of pi is declared as a double
double []estimatedPi = piColumn(hits,numThrows);
//total = total + the estimatation of pi
for(int i = 0; i < trials; i++){
totalPi += estimatedPi[i];
}
//Formatting the output
System.out.printf("%s %d %s %s", "Trial [",(counter + 1),"]", ": pi = ");
System.out.printf("%1.5f\n",estimatedPi[counter]);
}
//The average pi is the total pi's divided by the number of trials the user enters
double averagePi = (totalPi / trials / trials);
System.out.printf("%s %1.5f\n", "Estimation of pi = ",averagePi);
}
}
I was inspired by the question and wrote a comic project. I tried to make the code as more as possible object oriented, but stay in "domain" and do not use heavily design patterns, frameworks, etc. Also, I tried to follow test-first ideology. You can view commits history and see how the work went step by step.
Thank you, javacoder, for the experience and fun.

generating random numbers in java and finding percentage of how many are less than or equal to 50

My question is why isn't the code generating the amount of numbers that the users enters? Right now the code is only generating one number. Here is the original question given to me:
"In your main method, prompt the user for a number n. Write a method
called assessRandomness that generates a random number between 1 and
100 'n' times and return the percentage of times the number was less than
or equal to 50. Call your assessRandomness method from main and display
the result to the user from main. Do not interact with the user from
within the assessRandomness method."
output:
How many random numbers should I generate? 10
<assume the random numbers generated were 11 7 50 61 52 3 92 100 81 66>
40% of the numbers were 50 or less
my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("how many random numbers should I generate?: ");
int number = in.nextInt();
assessRandomness(number);
}
public static double assessRandomness(int n){
int random = (int)(Math.random()*100);
int randomNumbersLessthan50 = 0;
if (random <= 50)
{
double getPercentage = random/randomNumbersLessthan50;
}
else
{
System.out.println(random);
}
return random;
}
I don't see any kind of loop within assessRandomness.
Try
for(int x = 1; x <= n; x++){ ... }
as first line in assessRandomness, it should finally look like
public static double assessRandomness(int n){
int counterLessThan50 = 0;
for ( int x = 1; x <= n; x++)
if( (int)(Math.random()*100) <= 50 ) counterLessThan50++;
return (double) counterLessThan50 / n;
}
There's no repetition in your code to do something n times.
Here's one way to do it in one line using a stream:
public static double assessRandomness(int n) {
return Stream.generate(Math::random).limit(n).map(r -> r * 100 + 1).filter(r -> r <= 50).count() / (double)n;
}
Note that converting Math.random() to a number in the range 1-100 is pointless; this will give the same result:
public static double assessRandomness(int n) {
return Stream.generate(Math::random).limit(n).filter(n -> n < .5).count() / (double)n;
}
And is easier to read.
At the moment, your assessRandomness method never uses the variable n.
At first you should initialize a variable which counts the number of created randoms that are bigger than 50 (this will be your retutn value). You should then do a loop from 0 until n. For each loop run you should create a random value between 0 and 100. Then you should check wether the value is bigger than 50. If so, count up your previously created variable. When the loop has finished, return the count variable and print it in the main method.
This should help you understand better how to do something like this.
public static void main(String[] args) {
System.out.println("how many random numbers should I generate?: ");
Scanner in = new Scanner(System.in);
int number = in.nextInt();
int[] arrayPlaceHolderInMainMethod = new int[number];
arrayPlaceHolderInMainMethod = generateRandomNumberArray(number);
assessRandomness(arrayPlaceHolderInMainMethod);
}
public static void assessRandomness(int[] inputArray) {
int randomNumbersLessthan50 = 0;
int randomNumbersGreaterthan50 = 0;
int random = 0;
for (int i = 0; i < inputArray.length; i++) {
random = inputArray[i];
}
if (random <= 50) {
randomNumbersLessthan50 += 1;
} else {
randomNumbersGreaterthan50 += 1;
}
System.out.println(">50: " + randomNumbersGreaterthan50 + " Less: " + randomNumbersLessthan50);
}
public static int[] generateRandomNumberArray(int numberPickedByUser) {
int[] arrayOfRandomNumbers = new int[numberPickedByUser];
for (int i = 0; i < numberPickedByUser; i++) {
arrayOfRandomNumbers[i] = (int) (Math.random() * 100 + 1);
}
return arrayOfRandomNumbers;
}

Categories

Resources