The goal of this program is to take 2 random variables for a fraction and see if they are already in reduced terms or not. The supposed probability of this is 6/(pi^2). I run 1,000 different combinations of variables and determine how many were and were not already reduced. Then I solve for pi.
But the output is giving me "pi is 2.449489742783178" every time I run it.
Anyone know why? Thanks.
import java.util.*;
public class ratio1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int nonReducedCount = 0; //counts how many non reduced ratios there are
for(int i =1; i<=1000; i++){
Random rand = new Random();
int n = rand.nextInt(1000)+1; //random int creation
int m = rand.nextInt(1000)+1;
//Ratio ratio = new Ratio(n,m);
if (gcd(n,m)> 1 ){ // if the ratio was not already fully reduced
nonReducedCount++; // increase the count of non reduced ratios
}
}
int reducedCount = 1000 - nonReducedCount; //number of times the ratio was reduced already
double reducedRatio = reducedCount / nonReducedCount; //the ratio for reduced and not reduced
reducedRatio *= 6;
reducedRatio = Math.sqrt(reducedRatio);
System.out.println("pi is " + reducedRatio);
}
public static int gcd(int a, int b) { return b==0 ? a : gcd(b,a%b); }
}
When you divide two integers, you get integer division, with an integer result, even if you later assign the result to a double. Try
double reducedRatio = (double)reducedCount / nonReducedCount;
i.e. convert one of the operands to a double.
Related
I'm trying to make a small program that allows you to generate a certain amount of numbers within a range, but it does not work as expected.
For example, if I ask the program to generate 3 random numbers between 5 and 10 it gives me 5 random numbers between 0 and 5.
private void jFillActionPerformed(java.awt.event.ActionEvent evt) {
int intInput1;
int intInput2;
int intInput3;
int i;
int RandomNumber;
intInput1 = Integer.parseInt(txtInput1.getText());
intInput2 = Integer.parseInt(txtInput2.getText());
intInput3 = Integer.parseInt(txtInput3.getText());
int ListSize = (intInput3) + 1;
Random rnd = new Random();
for (i = 0; i <= ListSize; i++)
{
RandomNumber = rnd.nextInt((intInput2 - intInput1) + 1);
fill.addElement(RandomNumber);
lstNumbers.setModel(fill);
}
Simply always add 5 (or more specifically - intInput1 in your case as it seems it's lower range value) to generated numbers so it will be in the range you need (0+5=5, 5+5=10 so it will be in range 5,10)
Here an IntStream you can later than use limit to set the amount of numbers you want.
public static IntStream numbersBetween(int from, int to){
return new Random().ints().map(e -> Math.abs(e % ((to+1) - from)) + from);
}
I have an array with the total population of a country and another array with the total number of cases of COVID for each country. I need to divide the number of cases by the total population and store the percentage in a third array. I'm stuck on the syntax though and no one from my class is available for outreach until tomorrow. Can anyone please help me get past this step? I've tried lots of different ways of getting the new percentage array, but nothing works. I can't use int for the percentage because my professor wants it with four places after the decimal. No references in the examples or the book match what I'm trying to do.
Thanks in advance for your advice!
int[] cases = {10_036_282, 8_553_657, 5_675_032, 1_856_292, 1_781_997, 1_381_218, 1_250_499, 1_216_747, 1_149_068, 967_825};
int[] population = {327_096_265, 1_352_647_786, 209_469_323, 64_990_511, 145_734_038, 46_692_858, 44_361_150, 67_141_684, 49_661_048, 126_190_788};
//You must calculate the percentage of cases based on the number of cases and the population.
for (int i = 0; i < countries.length; i++){
double percentage[i] = ((cases[i] / population[i]) * 100);
}
Unless otherwise explicitly instructed, you should use doubles for percentages. Otherwise, cases[i] / population[i] is going to normally result in 0
double[] percentage = new double[...];
percentage[i] = ((cases[i] / (double)population[i]) * 100);
For simplification calculate everything just put into double and than convert the calculated value to int and store in the array.
Here you go!
import java.util.Queue;
import java.util.LinkedList;
import java.util.Arrays;
class Main{
public static void main (String[] args) {
int[] cases = {10_036_282, 8_553_657, 5_675_032};
int[] population = {327_096_265, 1_352_647_786, 209_469_323};
int[] percentage = new int[cases.length];
for(int i = 0; i < cases.length; i++){
double temp = ((double)cases[i] / (double)population[i] ) * 100;
int pr = (int) temp;
percentage[i] = pr;
}
System.out.println(Arrays.toString(percentage));
}
}
all of your number is in integer and division of integer by integer is an integer, at first you need to cast one or all of the values to double, and secondly you said with 4 decimal points so you need to format your decimal number as below:
int[] cases = { 10_036_282, 8_553_657, 5_675_032, 1_856_292, 1_781_997, 1_381_218, 1_250_499, 1_216_747,
1_149_068, 967_825 };
int[] population = { 327_096_265, 1_352_647_786, 209_469_323, 64_990_511, 145_734_038, 46_692_858, 44_361_150,
67_141_684, 49_661_048, 126_190_788 };
double[] average = new double[cases.length];
for (int i = 0; i < average.length; i++) {
average[i] = ((cases[i] / (double)population[i]) * 100.0);
average[i] = Double.parseDouble(String.format("%.4f", average[i]));
}
Hey I am trying to create a program that generates a random number that is only allowed to be used once. Sorry if that's confusing I'll try to explain. I want to have a program generate numbers from 1-100, but say if it generates 33, then for the rest of the number generation process 33 cannot be generated again, So I should end with exactly 100 different numbers. Any help is really appreciated, Thank you.
Here's my attempt so far
public class Seed {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a =0;
for (int i =0; i <20;i++) {
a = (int) Math.ceil(10 * Math.random()) ;
System.out.println(a);
int x = a;
System.out.println("This is x: " + x);
if (x == a )
{
a = (int) Math.ceil(10 * Math.random()) ;
}
}
}
}
Precompute a List containing all the required numbers, then shuffle it and remove elements each time you need to generate a new number. Eg:
List<Integer> numbers = new ArrayList<Integer>(100);
for (int i = 0; i < 100; ++i)
numbers.add(i);
Collections.shuffle(numbers);
int pick = numbers.remove(0);
int pick2 = numbers.remove(0);
I just started learning arrays so please explain in layman's terms if you can.
At around the 50th term of the array, negative numbers start appearing, which seems nonsensical given the code. I'm running this using eclipse (latest version as of 12/19).
public class Array1
{
/*
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
int[] tree = new int[1000];
tree[0] = 1;
tree[1] = 2;
int j = 0;
for (j = 1; j<999; j++)
{
tree[j+1] = tree[j] + tree[j-1];
}
for (int i=1; i<=150; i++)
{
System.out.println(tree[i]);
}
}
}
What you are computing is the sequence of Fibonacci numbers which are know to grow exponentially. Therefore, you eventually overflow your int, which causes it to become negative.
Integer overflow computing fibonacci numbers.
Read this article
int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm doing an assignment for my Data Structures class. we were asked to to study linear probing with load factors of .1, .2 , .3, ...., and .9. The formula for testing is:
The average probe length using linear probing is roughly
Success--> ( 1 + 1/(1-L)**2)/2
or
Failure--> (1+1(1-L))/2.
we are required to find the theoretical using the formula above which I did(just plug the load factor in the formula), then we have to calculate the empirical (which I not quite sure how to do). here is the rest of the requirements
**For each load factor, 10,000 randomly generated positive ints
between 1 and 50000 (inclusive) will
be inserted into a table of the
"right" size, where "right" is
strictly based upon the load factor
you are testing. Repeats are allowed.
Be sure that your formula for randomly
generated ints is correct. There is a
class called Random in java.util. USE
it! After a table of the right (based
upon L) size is loaded with 10,000
ints, do 100 searches of newly
generated random ints from the range
of 1 to 50000. Compute the average
probe length for each of the two
formulas and indicate the denominators
used in each calculationSo, for example, each test for a .5 load would have a table of > > size
approximately 20,000 (adjusted to be
prime) and similarly each test for a
.9 load would have a table of
approximate size 10,000/.9 (again
adjusted to be prime).
The program should run displaying the
various load factors tested, the
average probe for each search (the two
denominators used to compute the
averages will add to 100), and the
theoretical answers using the formula
above. .**
how do I calculate the empirical success?
here is my code so far:
import java.util.Random;
/**
*
* #author Johnny
*/
class DataItem
{
private int iData;
public DataItem(int it)
{iData = it;}
public int getKey()
{
return iData;
}
}
class HashTable
{
private DataItem[] hashArray;
private int arraySize;
public HashTable(int size)
{
arraySize = size;
hashArray = new DataItem[arraySize];
}
public void displayTable()
{
int sp=0;
System.out.print("Table: ");
for(int j=0; j<arraySize; j++)
{
if(sp>50){System.out.println("");sp=0;}
if(hashArray[j] != null){
System.out.print(hashArray[j].getKey() + " ");sp++;}
else
{System.out.print("** "); sp++;}
}
System.out.println("");
}
public int hashFunc(int key)
{
return key %arraySize;
}
public void insert(DataItem item)
{
int key = item.getKey();
int hashVal = hashFunc(key);
while(hashArray[hashVal] != null &&
hashArray[hashVal].getKey() != -1)
{
++hashVal;
hashVal %= arraySize;
}
hashArray[hashVal]=item;
}
public int hashFunc1(int key)
{
return key % arraySize;
}
public int hashFunc2(int key)
{
// non-zero, less than array size, different from hF1
// array size must be relatively prime to 5, 4, 3, and 2
return 5 - key % 5;
}
public DataItem find(int key) // find item with key
// (assumes table not full)
{
int hashVal = hashFunc1(key); // hash the key
int stepSize = hashFunc2(key); // get step size
while(hashArray[hashVal] != null) // until empty cell,
{ // is correct hashVal?
if(hashArray[hashVal].getKey() == key)
return hashArray[hashVal]; // yes, return item
hashVal += stepSize; // add the step
hashVal %= arraySize; // for wraparound
}
return null; // can’t find item
}
}
public class n00645805 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double b=1;
double L;
double[] tf = new double[9];
double[] ts = new double[9];
double d=0.1;
DataItem aDataItem;
int aKey;
HashTable h1Table = new HashTable(100003); //L=.1
HashTable h2Table = new HashTable(50051); //L=.2
HashTable h3Table = new HashTable(33343); //L=.3
HashTable h4Table = new HashTable(25013); //L=.4
HashTable h5Table = new HashTable(20011); //L=.5
HashTable h6Table = new HashTable(16673); //L=.6
HashTable h7Table = new HashTable(14243); //L=.7
HashTable h8Table = new HashTable(12503); //L=.8
HashTable h9Table = new HashTable(11113); //L=.9
fillht(h1Table);
fillht(h2Table);
fillht(h3Table);
fillht(h4Table);
fillht(h5Table);
fillht(h6Table);
fillht(h7Table);
fillht(h8Table);
fillht(h9Table);
pm(h1Table);
pm(h2Table);
pm(h3Table);
pm(h4Table);
pm(h5Table);
pm(h6Table);
pm(h7Table);
pm(h8Table);
pm(h9Table);
for (int j=1;j<10;j++)
{
//System.out.println(j);
L=Math.round((b-d)*100.0)/100.0;
System.out.println(L);
System.out.println("ts "+(1+(1/(1-L)))/2);
System.out.println("tf "+(1+(1/((1-L)*(1-L))))/2);
tf[j-1]=(1+(1/(1-L)))/2;
ts[j-1]=(1+(1/((1-L)*(1-L))))/2;
d=d+.1;
}
display(ts,tf);
}
public static void fillht(HashTable a)
{
Random r = new Random();
for(int j=0; j<10000; j++)
{
int aKey;
DataItem y;
aKey =1+Math.round(r.nextInt(50000));
y = new DataItem(aKey);
a.insert(y);
}
}
public static void pm(HashTable a)
{
DataItem X;
int numsuc=0;
int numfail=0;
int aKey;
Random r = new Random();
for(int j=0; j<100;j++)
{
aKey =1+Math.round(r.nextInt(50000));
X = a.find(aKey);
if(X != null)
{
//System.out.println("Found " + aKey);
numsuc++;
}
else
{
//System.out.println("Could not find " + aKey);
numfail++;
}
}
System.out.println("# of succ is "+ numsuc+" # of failures is "+ numfail);
}
public static void display(double[] s, double[] f)
{
}
}
You should take into account that Java's HashTable uses a closed addressing (no probing) implementation, so you have separate buckets in which many items can be placed. This is not what you are looking for in your benchmarks. I'm not sure about HashMap implementation but I think it uses open addressing too.
So forget about JDK classes.. since you want to calculate empirical values you should write your own version of an hashtable that uses the open addressing implementation with linear probing but you should take care of counting the probe length whenever you try to get a value from the hashmap..
For example you can write your hashmap and then take care of having
class YourHashMap
{
int empiricalGet(K key)
{
// search for the key but store the probe length of this get operation
return probeLength;
}
}
Then you can easily benchmark it by searching how many keys you want and calculating the average probe length.
Otherwise you can just provide the hasmap the ability of storing the total probe length and the count of gets requested and retrieve them after the benchmark run to calculate average value.
This kind of exercises must prove that the empirical value concordates with the theoretical one. So take also into account the fact that you may need many benchmarks, and then do the average of them all, assuring that variance is not too high.