I am trying to write a program that takes an integer as command-line argument, uses random to print N uniform random values between 0 and 1, and then prints their average value.
I'm not sure what arguments to put in the while loop so that random integers are repeated n times, n being the number from the user indicating the number of integers the random has to generate.
Any help would be appreciated.
enter code here
public class UniformRandomNumbers1 {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int i;
double total = 0.0; //(The sum of n, numbers)
for (i = 1; i <= n; i++) {
double rand = Math.random(); //(Random number between 0 & 1)
total += rand; // Increment total by rand
System.out.println(i + " = " + rand); // Prints value of n & corresponding double value
}
double average = total / n; // Calculates average of n numbers
System.out.println("Average = " + average); // Prints average of n numbers, Can i get an up vote? :) plz
}
}
if you just need to execute a loop a specific number of times, I'd use a for loop
The following loop will iterate exactly n times, and It's what I personally use when I need to do something exactly n times.
for(int i=0; i<n; i++)
{
//insert body here
}
int total = 0;
for (int current = 1; current <= n; n++) {
double rand = Math.random();
total += rand;
System.out.println(currentN + "= " + rand);
}
System.out.println("Total = " + total);
under the assumption that your PRNG is behaving correcly you just need this:
main()
{
printf("\n0.5");
exit(0);
}
that's for N sufficiently large... computed in constant time. otherwise use the moving average formula:
http://en.wikipedia.org/wiki/Moving_average
which requires only O(1) memory space instead of the naive O(N) approach
here the cut&paste java code:
public class Rolling {
private int size;
private double total = 0d;
private int index = 0;
private double samples[];
public Rolling(int size) {
this.size = size;
samples = new double[size];
for (int i = 0; i < size; i++) samples[i] = 0d;
}
public void add(double x) {
total -= samples[index];
samples[index] = x;
total += x;
if (++index == size) index = 0; // cheaper than modulus
}
public double getAverage() {
return total / size;
}
}
Related
I have:
salary = 2000;
n= salary/200 = 10 //number of loops;
contribution = 0.1, 0.2, 0.3, 0.4...;
I need to make a for loop that gets the sum of salary x contribution as:
salary x contribution1 = 500x0.1
salary x contribution2 = 500x0.2
...etc...
this is a method of my class:
public static double pensionContribution(double salary) {
double n = salary/200;
int n_round = (int) Math.floor(n);
int start = 1;
List<Integer> n_list = IntStream.rangeClosed(start, n_round)
.boxed().collect(Collectors.toList());
double counter = 0.1;
for (int i = 0; i < n_list.size(); i++) {
System.out.println(n_list.get((int) (salary*counter)));
}
counter = counter + 0.1;
//need the sum of all values of (salary*counter)
return n_round;
}
Thanks!
you can use this loop:
for(int i = 0;i < [times to loop];i++){
resultofmultiplication = (salary*counter)
sum = sum + resultofmultiplication
counter = counter + 0.1
}
return sum;
you will get all the results from the multiplications summed. idk why you need a list but this will give you the sum of the multiplications
For each n in the list you need to calculate salaryn0.1 and sum all.
This can be done in one stream:
public static double pensionContribution(double salary) {
double n = salary/200;
int n_round = (int) Math.floor(n);
return IntStream.rangeClosed(1, n_round).mapToDouble(i->salary*i*0.1).sum();
}
So I have an assignment where i'm supposed to create a program that generates 100 random integers and stores them in a single dimensional array. I am then supposed to calculate the average, standard deviation and variance. Through a lot of trial and error I was able to make a program that did this but what I missed was that it said to write a separate method for each property(average, standard deviation and variance). How would i go about doing that?
package homeassignment5;
public class HomeAssignment5 {
public static void main(String[] args) {
int n;
n = 100;
int[] random = new int [n];
for (int i = 0; i<random.length; i++)
random[i] = (int) (Math.random()* n);
double total = 0;
double average = 0;
double variance = 0;
double var = 0;
double sd = 0;
for (int element : random){
total += element;
average = total/n;
}
for (int i = 0; i<random.length; i++){
variance += (random[i] - average) * (random[i] - average);
}
var = variance / random.length;
sd = Math.sqrt(var);
//System.out.println("Total is: " + total);
System.out.println("Average is: " + average);
System.out.println("Variance is " + var);
System.out.println("Standard deviation is " + sd);
/*for (int i = 0; i<random.length; i++)
System.out.println(random[i]);
*/
}
}
Might be a bit of a mess but i'm really new to java and this was the product of a ton of trial and error.
So there are several ways of going about this, but the easiest would probably be this:
public class HomeAssignment5 {
private static int[] random;
public static void main(String[] args){
random = = new int[100];
...
}
public static void getAverage(){
// void if you want to print it here, double if you want to print in main
double average = 0;
int total = 0;
for(int i = 0; i < 100; i += 1)
total += random[i];
average = total / n; // you'll want to do this outside of the loop to
// to get the correct result!
System.out.println("Average: " + average);
}
...
}
You could alternatively pass the array to each method as a parameter.
By the way, in what you posted here, you still haven't actually written any random numbers into the array, so remember to do that, it's currently still all zero.
I believe this should help you..
All the functionalities are separated in form of methods,
the initialization is separated.
** WELCOME TO REFACTORING **
public class Refactor {
private int[] random;
private int n;
private double total = 0;
private double average = 0;
private double variance = 0;
private double sd = 0;
public Refactor(int n) {
this.n = n;
this.populateArray();
}
private void populateArray() {
random = new int[n];
for (int i = 0; i < random.length; i++)
random[i] = (int) (Math.random() * n);
}
public double getAverage() {
average = 0;
total = 0;
for (int element : random) {
total += element;
}
average = total / n;
return average;
}
public double getVariance() {
variance = 0;
for (int i = 0; i < random.length; i++) {
variance += (random[i] - average) * (random[i] - average);
}
variance = variance / random.length;
return variance;
}
public double getSD() {
this.getVariance();
sd = 0;
sd = Math.sqrt(variance);
return sd;
}
public static void main(String[] args) {
Refactor ref = new Refactor(100);
System.out.println("Average is: " + ref.getAverage());
System.out.println("Variance is " + ref.getVariance());
System.out.println("Standard deviation is " + ref.getSD());
}
}
How would i go about passing the array to each method?
The first and most straightforward of the three methods is average:
static double average(int [] r)
{ double total = 0;
for (int e: r) total += e;
return total/r.length;
}
For the second method, the standard deviation, I recommend not to pass the array, but rather the variance, since if the program has calculated the variance anyway, it need not be recalculated, and if it doesn't have, the SD method can be called with a call to the variance method as its argument.
static double SD(double variance) { return Math.sqrt(variance); }
For the third method, the variance, I recommend not only to pass the array, but also its average, with similar reasoning as above.
static double variance(int [] r, double average)
{ double var = 0;
for (int e: r) var += (e - average) * (e - average);
return var/r.length;
}
With those three methods defined, you can now replace
double total = 0;
double average = 0;
double variance = 0;
double var = 0;
double sd = 0;
for (int element : random){
total += element;
average = total/n;
}
for (int i = 0; i<random.length; i++){
variance += (random[i] - average) * (random[i] - average);
}
var = variance / random.length;
sd = Math.sqrt(var);
with
double average = average(random);
double var = variance(random, average);
double sd = SD(var);
I would like to generate an array of 100 numbers and find their average and sum. I am able to do this but I am not able to get the output of numbers into ascending order. I am super new to Java.
import java.util.Random;
public class randomNumberGen
{
public static void main(String [] args)
{
Random r=new Random();
double sum = 0; // is double so to prevent int division later on
int amount = 100;
int upperBound = 100;
for (int i = 0; i < amount; i++){
int next = r.nextInt(upperBound) + 1; // creates a random int in [1,100]
System.out.println(next);
sum += next; // accumulate sum of all random numbers
}
System.out.println("Your average is: " + (sum / amount));
System.out.println("Your sum is: " + (sum));
}
}
it is very easy. however I didn't see any array in your code. I create an example code for you. you can ask for more help.
public static void main(String[] args) {
SecureRandom random = new SecureRandom(); // it is better to use this library
double sum = 0; // is double so to prevent int division later on
int amount = 100;
int upperBound = 100;
int[] array = new int[amount]; // create an array with amount size
for (int i = 0; i < amount; i++) {
array[i] = random.nextInt(upperBound) + 1; // creates a random int in [1 , upperBound]
sum += array[i]; // accumulate sum of all random numbers
}
Arrays.sort(array); // sort array in default order which is ascending
System.out.println(Arrays.toString(array)); // toString is a way to print all of array, without iterate it and print it
System.out.println("Your average is: " + (sum / amount));
System.out.println("Your sum is: " + sum);
}
There are a lot of different sorting methods. For a beginner start with either Bubble Sort or Insertion Sort. Insertion Sort is slightly better as on average it runs slightly faster.
I offer to use one of special collections to sort numbers internally, without using one of sorting algorithms (e.g. us PriorityQueue):
public static void main(String[] args) {
final int amount = 100;
Random random = new SecureRandom();
Queue<Integer> queue = new PriorityQueue<>(amount, Comparator.naturalOrder()); // Comparator.reverseOrder() for reverse order
int sum = 0;
for (int i = 0; i < amount; i++) {
int val = random.nextInt(100) + 1;
sum += val;
queue.add(val);
}
System.out.println(Arrays.toString(queue.toArray()));
System.out.println("Your average is: " + (double)sum / amount);
System.out.println("Your sum is: " + sum);
}
I am trying to generate three random integers between 0 and 50, calculate the average, and print the result.
This is what I have so far:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package random.numbers;
import java.util.Random;
/**
*
* #author ericl_000
*/
public class RandomNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Random rand = new Random ();
int RandNum = 0;
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
}
int average = (RandNum);
System.out.println(average);
}
}
The output has the 3 random numbers, but the average is the last number of those 3 numbers. I don't know how to get the average of these 3 numbers. (I am new with Java.)
Your logic for calculating average is not correct, logic for average is:
average = (num1+num2+num3+... .... +num N)/N
So your logic for code should be:
Random rand = new Random();
int RandNum = 0;
float average = 0;
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
average = average+RandNum;
}
average = average/3;
System.out.println(average);
Example Code:
import java.util.Random;
public class RandomNumbers {
public static void main (String [] args) {
Random rand = new Random();
int randomNum = 0, total = 0;
int count = 3;
for(int i = 0; i < count; i++)
{
// This gives you 0 to 49, does not include 50!
randomNum = rand.nextInt(50);
System.out.println(randomNum);
// Keep track of total
total += randomNum;
}
// Average is well, total divided by count
int average = total / count;
System.out.printf("Average (Integer division): %d%n", average);
// Using double
double averageDouble = total / ((double) count);
System.out.printf("Average (Double division): %7.3f%n", averageDouble);
}
}
Output:
3
26
8
Average (Integer division): 12
Average (Double division): 12.333
Note:
Using integer or double for division will give u different results!
random#nextInt(int n) gives you a value between 0 (inclusive) and the specified value (exclusive), i.e. nextInt(50) will give you 0 to 49.
and how would you compute the average in real life? You add the numbers up, and you divide by 3.
int sum=0;
for(i=0; i<3; i++)
sum += rand.nextInt(50);
System.out.println(sum/3.0);
You are not saving the random numbers as they are generated.
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
}
For each iteration of the loop, a random number is generated and printed.
But is nowhere saved.Then how can you access them later to calculate the average.
Try something like this
for(int i =0; i < 3; i++)
{
RandNum += rand.nextInt(50);
}
This will add generated random number to already generated one.So bascially
RandNum will contain the sum at the end of all iterations of the loop.
Then you can use the following to print the average.
System.out.println(RandNum/3);
Just by naming a variable 'average', it wont find the average.You have to do the necessary calculation.ie.(sum/n).
Not sure why this is a complicated problem.
import java.util.Random;
public class RandomNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Random rand = new Random ();
int randCount = 3, randNum = 0, total = 0;
for(int i =0; i < randCount; i++) {
randNum = rand.nextInt(50);
System.out.println(randNum);
total = total + randNum;
}
int average = total/randCount;
System.out.println(average);
}
}
The average formula is the sum of all the numbers in a list divided by number by the number of items in that list. You can do this by constantly adding the random numbers up into a variable, lets call it x, then divide that by 3 (total number of items in that list).
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
int x += RandNum; //the += sign adds the current value of x to the value of RandNum
}
int average = (x/3);
System.out.println(average);
This answer assumes that you will be only using 3 random numbers.This is using ints however you should probably use doubles considering most averages aren't exact integers:
double RandNum = 0;
for(int i =0; i < 3; i++)
{
RandNum = rand.nextDouble(50);
System.out.println(RandNum);
double x += RandNum; //the += sign adds the current value of x to the value of RandNum
}
double average = (x/3);
System.out.println(average);
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random rand = new Random ();
int RandNum = 0;
int[] numbers = new int[]{rand.nextInt(50),rand.nextInt(50),rand.nextInt(50)};
double sum = 0;
for(int i =0; i < 3; i++)
{
System.out.println(numbers[i]);
}
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
System.out.println("Average value of array elements is : " + average);
}
}
import java.util.Scanner;
import java.util.Arrays;
public class Improved {
//I resize the array here so that it only counts inputs from the user
//I want to ignore the 0 input from the user
//I think the error happens here or in my main method
public static double[] resizeArray(double[] numbers, double size) {
double[] result = new double[(int)size];
for (int i = 0; i < Math.min(numbers.length, size); ++i) {
result[i] = numbers[i];
}
return result;
}
//compute average nothing is wrong here
public static double getAverage( double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; ++i)
sum += numbers[i];
double average = sum/numbers.length;
return average;
}
//SD nothing is wrong here
public static double getSD( double[] numbers, double average) {
double sd = 0;
for ( int i = 0; i < numbers.length; ++i)
sd += ((numbers[i] - average)*(numbers[i] - average)/ numbers.length);
double standDev = Math.sqrt(sd);
return standDev;
}
//maximum nothing is wrong here
public static double getMax( double[] numbers) {
double max = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] > max){
max = numbers[i];
}
return max;
}
//minimum nothing is wrong here
public static double getMin( double[] numbers) {
double min = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] < min) {
min = numbers[i];
}
return min;
}
//median value nothing is wrong here
public static double getmed( double[] numbers) {
double median;
if (numbers.length % 2 == 0)
median = (((numbers[numbers.length/2 - 1])
+ (numbers[numbers.length/2]))/2);
else
median = numbers[numbers.length/2];
return median;
}
//the problem is in the main method i think or in the call method to resize
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] statArr = new double[99];
double size = 0;
int i = 0;
System.out.println("Type your numbers: ");
double number = input.nextDouble();
//I don't want the zero in the array, I want it to be excluded
while (number != 0){
statArr[i] = number;
i++;
number = input.nextDouble();
++size;
if ( size == statArr.length) {
statArr = resizeArray(statArr, statArr.length * 2);
}
++size;
}
statArr = resizeArray(statArr, size);
java.util.Arrays.sort(statArr);
double average = getAverage(statArr);
System.out.println( "The average is " + getAverage(statArr));
System.out.println( "The standard deviation is " + getSD(statArr, average));
System.out.println( "The maximum is " + getMax(statArr));
System.out.println( "The minimum is " + getMin(statArr));
}
}
// I don't have any concerns with computing the math parts, but I can't seem to make it so my array ignores the 0 that ends the while loop. In other words, I want every number included up until the user enters the number 0. Everything else is right. Thank you very much!
You have ++size twice. This means your resizeArray method won't work correctly:
double[] result = new double[(int)size];
Here you're allocating more than what you actually want. This is why you're getting zeroes in your array. Java arrays are initialized to 0 (in case of numeric primitive types).
As Giodude already commented, I suggest you using List implementations (typically ArrayList) instead of arrays everytime you can.
Also size could be declared as int altogether and avoid that cast (and save some extremely slight memory), you're not using it as a double anywhere.