How do I sum the elements of an array list? - java

I'm trying to use a while loop to display the results of some calculations.
Each iteration through the loop divides two numbers, increments one number twice, stores the result in an array list, and is supposed to sum all the elements in the array list.
However, the result of my sum is incorrect and I can't seem to figure out why. I should be getting 1956.9272 but it displays 73.3576, any idea what I'm doing wrong?
Here's my code:
import java.util.ArrayList;
public class testtest {
public static void main(String[] args) {
// Initialize variables
double num1 = 1;
double num2 = 3;
double sum = 0;
// A new array list is created
ArrayList<Double> myCalc = new ArrayList<Double>();
// While loop is started if num2 is lass than 99
while (num2 <= 99) {
//Divides 1 by num2
double answer = num1 / num2;
// Adds the result to the array list
myCalc.add(answer);
// Twice increments num2, which is the denominator
++num2;
++num2;
// For loop iterates through each element in the array list
for (Double result : myCalc) {
// Sums all the elements in the array list
sum += result;
}
}
// Displays the results of adding the array list elements together
System.out.printf("%.4f", sum);
}
}

double n1 = 1, n2 = 3, result, sum = 0;
ArrayList<Double> list = new ArrayList<>();
while( n2 <= 99) {
result = n1/n2;
list.add(result);
n2 += 2;
}
for(double temp: list)
sum = sum + temp;
System.out.println(sum); //1.9377748484749076
If you put the for loop inside while you get
double n1 = 1, n2 = 3, result, sum = 0;
ArrayList<Double> list = new ArrayList<>();
while( n2 <= 99) {
result = n1/n2;
list.add(result);
n2 += 2;
for(double temp: list)
sum = sum + temp;
}
System.out.println(sum); //73.35762984798366

You are doing sum(k = 1 to 49) of 1/(1+2k) * (49+1-k). Or in java:
double sum = 0;
for (int k = 1; k < 50; ++k) {
sum += (50.0 - k)/(1 + 2*k);
}
This indeed is near to 73.
I can only guess that the original specifation also changed num1 or more likely
answer must be added to every array element also.

For debugging purposes, let's do the following:
Add double ans = 0.0; under // Initialize variables
Add ans = ans + answer; followed by System.out.printf("%.4f %.4f %.4f = %.4f\n", num1, num2, answer, ans); under double answer = num1 / num2;
This will show the running total and the incremental additions to the total. I get
1.0000 3.0000 0.3333 = 0.3333
1.0000 5.0000 0.2000 = 0.5333
1.0000 7.0000 0.1429 = 0.6762
1.0000 9.0000 0.1111 = 0.7873
...
1.0000 99.0000 0.0101 = 1.9378
So, perhaps the assignment has the wrong total, or there is something that you have not included.

Related

Calculating sum of odd numbers between two user inputs

I am trying to calculate the sum of the odd numbers between two user inputted numbers.
This is the code I have so far:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = s.nextInt();
System.out.print("#2: ");
int num2 = s.nextInt();
int sum = 0;
for (int i = num1; i <= num2; i += 2) {
sum = sum + i;
}
System.out.print(sum);
}
}
When I input 3 and 11, it outputs 35, which is correct.
However, with 4 and 20, it outputs 108, which is not correct. It should instead be 96.
Where have I gone wrong in the code?
You need to check if the first number is even or odd first, because if it is even, it is going to sum the even numbers instead of odd ones since you are increasing "i" by 2 after every iteration. Try adding the line below before the for loop.
if(num1%2==0){num1++);
Explanation
Your loop sums the even numbers if you start with an even number.
Check your code:
for (int i = num1; i <= num2; i += 2)
Assume num1 is even, e.g. 4. Then your loop starts with i = 4. And then you continue with += 2, so you end up with 6, 8, 10, ..., i.e. the even numbers.
Solution
You can simply fix it by patching num1 before your loop.
// Put this before your loop
if (num1 % 2 == 0) { // checks if num1 is even
num1++;
}
This way you will start with 5 then, and then get 7, 9, 11, ....
To sum a range of numbers:
Take the average of the first number and the last number, and multiply by the number of numbers.
But, first you need to make sure you lower and upper bounds are odd numbers. This is actually what is the problem with the code in the question.
Once that is done, calculate the average number, and the number of numbers:
public static long sumOddNumbers(int min, int max) {
long minOdd = (min % 2 == 1 ? min : min + 1); // Round up to odd number
long maxOdd = (max % 2 == 1 ? max : max - 1); // Round down to odd number
if (minOdd > maxOdd)
return 0;
// average = (minOdd + maxOdd) / 2
// count = (maxOdd - minOdd) / 2 + 1
// sum = count * average
return ((maxOdd - minOdd) / 2 + 1) * (minOdd + maxOdd) / 2;
}
Test
System.out.println(sumOddNumbers(3, 11)); // prints: 35
System.out.println(sumOddNumbers(4, 20)); // prints: 96
This can be done easily with a mathematical formula. But based on your question I presume you want to use a loop so here goes.
An odd number has the low order bit set to 1.
If the number is already odd, resetting that bit has no effect so it is still odd.
But setting that bit for an even number makes it the next higher odd number.
So use the bitwise OR operator.
3 | 1 = 3
4 | 1 = 5
And do the following:
int start = 4;
int end = 20;
int sum = 0;
for (int i = (start | 1); i <= end; i += 2) {
sum += i;
}
System.out.println(sum);
If you want to use streams in Java 8+ you can do it this way.
int sum = IntStream.rangeClosed(start, end).filter(i -> i & 1 == 1).sum();
And the formula I was talking about is the following, derived using simple series summation.
For ints, start and end
start |= 1; // ensure start is next odd number
end = (end | 1) - 2;// ensure end is last odd - 2
int sum = ((start + end) * ((end - start) / 2 + 1)) / 2;
If the two numbers are natural numbers, you can apply the formula:
Sum of odd natural numbers from m to n = sum of natural odd numbers up to n - sum of natural odd numbers up to m
= (n/2)^2 - (m/2)^2
where n is an even number or the next even number in case it is an odd number
In the program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = Math.abs(s.nextInt());
System.out.print("#2: ");
int num2 = Math.abs(s.nextInt());
System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));
num1 = 5;
num2 = 15;
System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));
num1 = 5;
num2 = 16;
System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));
num1 = 6;
num2 = 15;
System.out.println("Sum of natural odd numbers from "+num1+" to "+num2+" = "+sumNaturalOddOfRange(num1,num2));
}
static int sumNaturalOddOfRange(int num1, int num2) {
if(num2%2==1)
num2++;
return (int)(Math.pow(num2 / 2, 2) - Math.pow(num1 / 2, 2));
}
}
A sample run:
#1: 10
#2: 20
Sum of natural odd numbers from 10 to 20 = 75
Sum of natural odd numbers from 5 to 15 = 60
Sum of natural odd numbers from 5 to 16 = 60
Sum of natural odd numbers from 6 to 15 = 55
**Here is the answer**
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("#1: ");
int num1 = s.nextInt();
System.out.print("#2: ");
int num2 = s.nextInt();
int sum = 0;
if (num1%2==0) {
num1++;
}
for (int i = num1; i <= num2; i++) {
sum +=i;
}
System.out.print(sum);
}

Sum and Averages of an Array

I am working on an array problem for my college course and I'm trying to find the sum and the average of an array. Here's the code I have so far.
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
//declare the array values
weeks[0]= 2;
weeks[1]= 4;
weeks[2]= 8;
weeks[3]= 10;
weeks[4]= 14;
weeks[5]= 16;
weeks[6]= 20;
weeks[7]= 22;
weeks[8]= 24;
weeks[9]= 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
I know that the average works but I'm stuck on the sum. The problem I'm having is I cant seem to initialize the values in the array so that I can provide a sum for them. What am I doing wrong or what am I missing?
You have two problems in your code;
A) For-loop assignment
You don't need to make the first assignment, just adding sum to the week[index] is ok;
for (int index = 0; index < weeks.length; index++)
sum = sum + weeks[index];
B) Calculating the average
Sum is defined as an int which is a primitive integer, because of that, the division of an integer to an integer, the output is an integer which is not precise. Output of the division (45/10) is casted to integer, then assigned to double which is rounded off to 4, then casted to double again, and '4.0' became the result.
To avoid this unprecise result, cast sum to the double as below;
average = (double)sum / weeks.length;
The corrected version of your code is as below;
Demo
public class Module55 {
public static void main(String args[]) {
// declare the array to have 10 items for 10 weeks
// also declare sum as an int and average as a double to accommodate for
// decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
// declare the array values
weeks[0] = 2;
weeks[1] = 4;
weeks[2] = 8;
weeks[3] = 10;
weeks[4] = 14;
weeks[5] = 16;
weeks[6] = 20;
weeks[7] = 22;
weeks[8] = 24;
weeks[9] = 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++)
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = (double)sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
Output
The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6
And a note for scope
And one last note about the scope, check out this code;
for (int index = 0; index < weeks.length; index++)
weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
In the for-loop, because that no brackets are used, only the first statement under the for-loop will be considered in the scope of the loop by the compiler. That's why, for the next line, the compiler is giving error about the index because index is defined inside the scope of the for-loop.
you need to use brackets in your for loop. currently your code is evaluating like this:
for (int index = 0; index < weeks.length; index++)
{
weeks[index] = index;
}
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
you want your code to evaluate like this
for (int index = 0; index < weeks.length; index++)
{
weeks[index] = index; //logical issue, what does this line achieve?
sum = sum + weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);
This will at least solve your procedural problems but you will still need to take a look at your logic. Try using breakpoints to debug your code.
A very simple way to achieve this in Java 8 is to use the built in mechanisms for gathering statistics:
int[] weeks = {3, 4, 6, 9, 10};
IntSummaryStatistics stats = IntStream.of(weeks).summaryStatistics();
System.out.println("sum = " + stats.getSum() + "; average = " + stats.getAverage());
for (int i = 0;i < weeks.length) {
sum += weeks[i];
}
System.out.println("Sum is:" + sum);
First of all, you simply don't need the line weeks[index] = index;.
And for average you have to cast the sum to double if you want to get the average in double as you have declared the sum as int.
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = {2,4,8,10,14,16,20,22,24,26};
int sum = 0;
double average = 0;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++)
//weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = (double)sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6
Summing an array of numbers and dividing by n to get the average like this will not get the correct value - you should not compute the average using integer division.
Also, this approach might work for the example shown, but not in general. For example, try using this code to find the average of these two value: (INT_MAX-6) and (INT_MAX-2).
The corrected code. While calculating average you have cast on of the varibale to double else you will get the average as integer
public class Mod55 {
public static void main(String args[]) {
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
int sum = 0;
double average = 0;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) {
sum += weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0) {
average = (double)sum / weeks.length;
} else {
average = 0;
}
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
Java8 You could achieve the same thing like this.
int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
int sum = Arrays.stream(weeks)
.sum();
double average = Arrays.stream(weeks).average().orElse(0);
you can find this handy with lambdas.The code looks something like this.
int weeks[] = {1,2,3,4};
List<Integer> asd = IntStream.of(weeks).boxed().collect(Collectors.toList());
//asd.forEach(System.out::println);
//this outputs average
System.out.println(asd.stream().mapToDouble(val -> val).sum()/asd.size());
//this outputs sum
System.out.println(asd.stream().mapToInt(val -> val).sum());
//another way to achieve this thanks to commenter
System.out.println(IntStream.of(asd).summaryStatistics());

Mean, Median, Variance calculator

I have created a program that calculates the mean, median, and variance. the program accepts up to 500 inputs. All of my methods work perfectly when there are 500 inputs (max size of my array). When there are less inputs, only the 'mean' calculator works. Here's the entire program:
public class StatsPackage{
static int i = 0, arrayLength;
static double sum = 0, mean, median, sumOfSquares, variance, stdDev;
static double calcMean (int inputs[], int count) throws IOException{
for (i = 0; i < count; i++){
sum += inputs[i];
}
mean = (sum/count);
return mean;
}
static double calcMedian (int inputs[], int count){
Arrays.sort(inputs);
if (count % 2 == 0){
median = ((inputs[(count/2)] + inputs[(count/2)- 1])/2) ;
}
if (count % 2 != 0){
median = inputs[(count-1)/2];
}
return median;
}
static double calcVariance (int inputs[], int count){
sum = 0;
for (i = 0; i < count; i++){
sumOfSquares += (inputs[i]*inputs[i]);
}
for (i = 0; i < count; i++){
sum = sum + inputs[i];
}
variance = ((sumOfSquares/count) - (sum * sum)/(count * count));
return variance;
}
static double calcStdDev (double varianceInput){
stdDev = Math.sqrt(variance);
return stdDev;
}
public static void main(String[] args) throws IOException {
NumberFormat nf = new DecimalFormat("0.##");
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
String str = "test";
int inputs[] = new int [500];
int counter = 0;
int i = 0;
while ((str = stdin.readLine()) != null && i < 500) {
inputs[i] = Integer.parseInt(str);
i++;
counter++;
}
System.out.println("Mean: " + nf.format(StatsPackage.calcMean(inputs, counter)));
System.out.println("Median: " + nf.format(StatsPackage.calcMedian(inputs, counter)));
System.out.println("Variance: " + nf.format(StatsPackage.calcVariance(inputs, counter)));
System.out.println("Standard Deviation: " + nf.format(StatsPackage.calcStdDev(variance)));
}
}
Here is an example output when 10 random numbers are entered:
Mean: 47.90
Median: 0.00
Variance: 0.00
Standard Deviation: 0.00
Here is the same code when 500 numbers are entered (the max size of my array):
Mean: 47.27
Median: 47.00
Variance: 856.71
Standard Deviation: 29.27
These outputs are consistent. I input 10 numbers, and I only get the mean method to work. I input 500 numbers and I get all of them working. I'm running this program against another tester program, not by inputting the numbers myself in eclipse. The tester program is my instructor's and I trust his program is working correctly.
Can anyone please help? I'm about to tear my hair out.
The problem is that you are initializing an array of size 500, but then not using all 500 indices. That means you have an array like:
[2,5,3,7,8,2,......,0,0,0,0,0,0,0,0,0,0,0,0]
So your code is going to calculate the median and std devation with all those 0s. What you should be using is an ArrayList. An ArrayList will expand in size as you add elements, whereas a regular list cannot change size.
If you cannot use an ArrayList, then you have to do a bit more work.
while ((str = stdin.readLine()) != null && i < 500) {
inputs[i] = Integer.parseInt(str);
i++;
counter++;
}
Your counter variable already has the information you need. Now, before passing this array to your mean/median/stddev methods, you need to reduce the size of the array. The easiest way to do this is to use an existing method provided to all arrays, called CopyOf() : CopyOf() method for Arrays
int[] newArray = Arrays.copyOf(inputs, counter);
Now replace your old input array with your new newArray in your method calls:
System.out.println("Mean: " + nf.format(StatsPackage.calcMean(newArray, counter)));
System.out.println("Median: " + nf.format(StatsPackage.calcMedian(newArray, counter)));
System.out.println("Variance: " + nf.format(StatsPackage.calcVariance(newArray, counter)));
System.out.println("Standard Deviation: " + nf.format(StatsPackage.calcStdDev(variance)));
I assume you tested it with random positive integers, as it seems to be the case for these results.
When you input n (where n is small in comparison to 500) positive integers, your array is mostly full of 0's.
As Array.sort sorts the array in-place, calcMedian modifies the actual array passed, placing all these 0's to the front, and the median is, naturally, 0, as all n of them are in the back.
Then calcVariance calculates the variance of the first n 0's, as the array was sorted previously.
Finally, calcStdDev refers to the result of calcVariance.
To fix this, you should consider:
Sorting the array with this method taking a starting and ending indices.
Making a copy of the array before sorting.
Keeping the class stateless - all these methods could take anything required as arguments (while this is not strictly necessary, it will save you a lot of time in the future).
Your method of calculating variance is wrong. Have a look at the definition of the variance (for instance on wikipedia).
import java.util.Arrays;
public class StatisticalCalculations {
public static void main(String[] args) {
double[] array = { 49, 66, 73, 56, 3, 39, 33, 77, 54, 29 };
double mean = getMean(array);
double var = getVariance(array);
double med = getMedian(array);
System.out.println(Arrays.toString(array));
System.out.println("mean : " + mean);
System.out.println("variance : " + var);
System.out.println("median : " + med);
}
private static double getMean(double[] array) {
int l = array.length;
double sum = 0;
for (int i = 0; i < l; i++)
sum += array[i];
return sum / l;
}
private static double getVariance(double[] array) {
double mean = getMean(array);
int l = array.length;
double sum = 0;
for (int i = 0; i < l; i++)
sum += (array[i] - mean) * (array[i] - mean);
return sum / l;
}
private static double getMedian(double[] array) {
int l = array.length;
// copy array to leave original one untouched by sorting
double[] a = new double[l];
for (int i = 0; i < l; i++)
a[i] = array[i];
Arrays.sort(a);
if (l % 2 == 0)
return (a[l / 2 - 1] + a[l / 2]) / 2;
else
return a[(l - 1) / 2];
}
}
Also, you have an issue with your array, as it is fixed size versus a variable size of user inputs. Consider using ArrayList<Double> or something similar as a container for your values to avoid this problem.

Java: Dividing pairs from an Array

I am working on a project and am stuck on what to do next. I need to write a Java program that accepts from a user ten values and place those numbers in an array. The numbers in the array will be added together and the result displayed to the user. (I got that part)
Here is the problem: The program should compare the values for elements 1 and 2 (in the array) and divide the larger number by the smaller number. It should compare the values for all odd/even elements and divide the larger by the smaller value.
I do not know how to do this at all. I started with if-else statements but I am getting errors. It know it's a mess right now, but any help with dividing the array pairs would be very helpful. Send me links too, I have been unsuccessful finding any, so I can learn more.
Thanks!
Here is what I have so far:
/import java.util.Scanner;
public class ExceptionHandler {
/**
* #param args the command line arguments10
* 10
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter ten values:");
System.out.println();
// Input the data from the user.
int[ ] digit = new int[11];
int sum = 0;
//Declare an array
for (int i = 1; i < digit.length; i++) {
System.out.print("Value " + i + ": ");
digit[i] = in.nextInt();
sum += digit[i];
}
System.out.println("Total Values in Array:"+ sum);
// Calculate the sum and print the total
System.out.println("Would you like to divide values?");
// Fix this later
int result= digit[i];
if (digit[i] > digit[i + 1])
result = digit[i] / digit[i + 1];
else {
(digit[i + 1] / digit[i]);
}
// Compare element 0 with 1, divide larger element by smaller element
if (digit[i])> digit[i + 3])
result = digit[i] / digit[ i+ 3];
else{
(digit[i +3])/ digit[i];
}
}
You are using int for the division. Use a double instead, as it can divide two integers with decimal point precision.
// needed for division
double[] digit = new double[11];
for (int i = 0; i < digit.length; i++)
{
digit[i] = (double)in.nextInt;
sum += (int)digit[i];
}
//you can use this variable if needed, if not, ignore it
double[] divisionResult = new double[digit.length / 2];
for(int i = 1; i < digit.length; i += 2) {
double result = digit[i];
if (result > digit[i + 1])
result = result / digit[i + 1];
else {
result = digit[i + 1] / result;
}
divisionResult[i / 2] = result;
System.out.println(result);
}
EDIT: I'm also not sure why you're using
for(int i = 1; i < 11; i++)
Because you used that, I used it similarly above, but the actual convention should be:
for(int i = 0; i < 10; i++)
Doesn't make a huge difference, but better to follow good coding conventions :)
You can just use a for loop:
for (int i = 0; i < 10; i += 2) {
if (digit[i] > digit[i + 1]) {
result = digit[i] / digit[i + 1];
}
else {
result = digit[i + 1] / digit[i];
}
System.out.println(result);
}
This should work if I got it right what you want:
for (int i = 0; i < array.length; i = i+2) {
int firstDigit = array[i];
int secondDigit = array[i+1];
if (firstDigit > secondDigit) {
return firstDigit / secondDigit;
} else {
return secondDigit / firstDigit;
}
}
You iterate over the array and compare the first with the second element. By increasing your counterVariable (i) by two you always compare the 1st / 2nd, 3rd / 4th and so on numbers of the array.
Hope this helps :)
You variable i is local to the for loop in your code. If you want to use i again, you need to declare it outside of the loop to for you to use it outside the scope of the for loop. In addition, the last value of "i" here is the last array index, which would throw on array out of bound exception anyway (in other words you need to make another loop where you initialize "i" to 0 again under your "Would you like to divide values?" statement). Lastly, you need to do an assignment, so
(digit[i + 1] / digit[i]);
is not a valid statement. If you want to write it into result, you need to write:
result = (digit[i + 1] / digit[i]);
and if you want to override in place you can use
digit[i+1] = (digit[i + 1] / digit[i]);
or
digit[i + 1] /= digit[i];

help for a java assignment

I have created a method to create some random double values for example 10 values : num1, num2, …num10 which sum of this 10 values is 1 : num1+num2+…+num10 = 1
My method is like the method in forum
Getting N random numbers that the sum is M :
private static double[] randSum(int n, double m) {
Random rand = new Random();
double randNums[] = new double[n], sum = 0;
for (int i = 0; i < randNums.length; i++) {
randNums[i] = rand.nextDouble();
sum += randNums[i];
}
for (int i = 0; i < randNums.length; i++) {
randNums[i] /= sum * m;
}
return randNums;
}
But this method create very long numbers like: 0.18593711849349975
I even used Math.round() method but with this method my numbers are 0.0, 0.5, 0.0 , …
I need numbers from 0.01 to 0.99 or 0.1 to 0.9. If I was using integer numbers I could do this with something like Random.nextInt(0.98) +0.01 , but nextDouble() method doesn’t accept parameters, how can I do this? Would you please help me? thanks
You could generate integers via nextInt, and then divide them by the required power of 10.
Generate nextDouble(); and round it using this method
public static double round(double d, int decimalPlace){
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
double d = 3.1537;
// output is 3.2
System.out.println(d + " : " + round(d, 1));
// output is 3.15
System.out.println(d + " : " + round(d, 2));
// output is 3.154
System.out.println(d + " : " + round(d, 3));
Source
Multiply your number by 100 and round the result. That will give you the original number with the insignificant digits stripped off. Then subsequently divide the result by 100 to get back to the original scale.
x = Math.round(x*100.0) / 100.0;
If you want to use 2 decimals, you could do it as follows:
private static double[] randSum(int n, double m){
double[] randoms = new double[n];
int valueLeft = (int) (m * 100);
for(int i = 0; i < n-1; i++){
int tempRand = (int)(Math.random() * valueLeft);
randoms[i] = (double)tempRand / 100;
valueLeft -= tempRand;
System.out.println(tempRand + " " + randoms[i] + " " + valueLeft);
}
randoms[n-1] = (double)valueLeft/100;
return randoms;
}

Categories