double Hg = Double.parseDouble(values2[17]);
for (int i = 0; i < 3; i++) {
double Avg = (Hg + Hg + Hg) / 3;
System.out.println(Avg);
}
My program reads a file and puts everything in a String array called values2. The array element #17 (values2[17]) contains the values I need. I converted that array element into a double so I could then calculate the average. The program should take the first 3 values that are in values[17] and then divide by 3 to calculate the average, but it is just printing out the same values 3 times instead of adding and then dividing.
Any thoughts of what I am doing wrong?
If I understand what you're doing (comma seperated String of values), it could be as simple as...
public static void main(String[] args) {
String[] values = new String[18];
values[17] = "1.0, 2.0, 4.0";
double total = 0;
int count = 0;
for (String v : values[17].split(",")) {
if (v != null) {
total += Double.valueOf(v.trim());
count++;
}
}
double avg = total / ((double) count);
System.out.println("The average of " + values[17] + " is " + avg);
}
Which outputs
The average of 1.0, 2.0, 4.0 is 2.3333333333333335
If values2[17] is a String like "2 5 7", Then you need to parse all them each individually
String[] nums = valus2[17].split(" ");
double d1 = Double.parseDouble(num[0]);
double d2 = Double.parseDouble(num[1]);
double d3 = Double.parseDouble(num[3]);
double average = (d1 + d2 + d3) / 3;
On The other hand if you you have a String like "567" and you want the individual values, can you split into a char array then add the int values
String value = "567" // value2[17]
char[] digits = value.toCharArray();
int total = 0;
for (char c : digits){
total += Integer.parseInt(String.valueOf(c));
}
double average = total / new Double(digits.length);
You don't do anything with the i...
double total= 0.0;
for(int i = 0; i < 3;i++) {
total += values[i];
}
double avarage = total/3.0;
System.out.println(avarage);
Currently you are adding the whole array to itself 3 times then dividing but you need to add the three ideas in the array then divide by three
do
double Avg = values2[0] + values2[1] + values2[2] / 3
Related
I have to write a Taylor series until the 16th element that calculates sin and compare the values returned values with Math.sin. Well , everything works fine until the last time when instead of 0.00000 i get 0.006941.Where is my error and if somebody have an idea how to write this in a more professional way I would be very happy.
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
NumberFormat formatter = new DecimalFormat("#0.000000");
double val[] = {0, Math.PI / 3, Math.PI / 4, Math.PI / 6, Math.PI / 2, Math.PI};
for (int i = 0; i < val.length; i++) {
System.out.println("With Taylor method: " + formatter.format(Taylor(val[i])));
System.out.println("With Math.sin method: " + formatter.format(Math.sin(val[i])));
}
}
public static double Taylor ( double val){
ArrayList<Double> memory = new ArrayList<Double>();
double row = val;
for (int i = 0, s = 3; i < 16; i++, s = s + 2) {
double mth = Math.pow(val, s);
double result = mth / factorial(s);
memory.add(result);
}
for (int i = 0; i < 16; i++) {
if (i % 2 == 0) {
double d = memory.get(i);
row = row - d;
} else {
double d = memory.get(i);
row = row + d;
}
}
return row;
}
public static long factorial ( double n){
long fact = 1;
for (int i = 2; i <= n; i++) {
fact = fact * i;
}
return fact;
}
}
Your math is correct, but your factorials are overflowing once you get to calculating 21!. I printed out the factorials calculated.
factorial(3) = 6
factorial(5) = 120
factorial(7) = 5040
factorial(9) = 362880
factorial(11) = 39916800
factorial(13) = 6227020800
factorial(15) = 1307674368000
factorial(17) = 355687428096000
factorial(19) = 121645100408832000
factorial(21) = -4249290049419214848 // Overflow starting here!
factorial(23) = 8128291617894825984
factorial(25) = 7034535277573963776
factorial(27) = -5483646897237262336
factorial(29) = -7055958792655077376
factorial(31) = 4999213071378415616
factorial(33) = 3400198294675128320
It appears that your raising val to ever higher powers isn't significant enough to make a difference with the overflow until you get to the highest value in your array, Math.PI itself. There the error due to overflow is significant.
Instead, calculate each term using the last term as a starting point. If you have the last value you entered into memory, then just multiply val * val into that value and then divide the next two numbers in sequence for the factorial part.
That's because memory.get(i) is equal to memory.get(i - 1) * (val * val) / ((s - 1) * s). This also makes your calculation more efficient. It avoids the multiplication repetition when calculating the numerator (power part) and the denominator (the factorial calculation). This will also avoid the overflow which results from how you calculated the denominator separately.
My implementation of this idea substitutes this for the first for loop:
double mth = val;
for (int i = 0, s = 3; i < 16; i++, s = s + 2) {
mth = mth * val * val;
mth = mth / ((s - 1) * s);
memory.add(mth);
}
and places
double row = val;
between the for loops, to ensure that the first term is the initial sum as you had it before. Then you don't even need the factorial method.
This this I get 0.000000 for Math.PI.
I made the arithmetic mean for whole the sorted array, but now i want to make the arithmetic mean for first sorted half and second sorted half of array.
Ex: My array is: 77, 99, 44, 55, 22, 88, 11, 00, 66, 33.
My code make in first place the sort.
The outcome of program is: 00 11 22 33 44 55 66 77 88 99.
Now i want to make the mean for first half:
00 11 22 33 44 and print it.
Then i want to make the mean for the second half:
55 66 77 88 99 and print it.
public class Array {
private double[] a;
private int NrElmts;
public Array(int max)
{ a = new double[max];
NrElmts = 0;
}
public void elements(double value)
{ a[NrElmts] = value;
NrElmts++;
}
public void print()
{ for(int j=0; j<NrElmts; j++)
System.out.print(a[j] + " ");
System.out.println("");
}
public void selectionSort()
{
int out, in, min;
for(out=0; out< NrElmts -1; out++)
{ min = out;
for(in=out+1; in< NrElmts; in++)
if(a[in] < a[min] )
min = in;
invertPositions(out, min); }
}
private void invertPositions(int one, int two)
{ double temp = a[one];
a[one] = a[two];
a[two] = temp;
}
public void mean()
{
int i;
double sum = 0;
for(i = 0; i < NrElmts; i++) {
sum+=a[i];}
double medie = sum/NrElmts;
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
}
Try this
public void firstHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts/2;
for (i = 0; i < NrElmts/2; i++) { // take sum only till half.
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half the elements
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
public void secondHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts % 2 == 0 ? NrElmts/2 : NrElmts/2 + 1; // If odd, this second array will contain one more element.
for (i = NrElmts/2; i < NrElmts; i++) { // take sum for the next half
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half elements (half + 1) in case of odd length.
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
To calculate the mean for 9, 2 and 7 you have to firstly add them all up, which equals 18 and then divide by how many there are - so 18 / 3 which is 6.
Although, you will have to account for the possibility of an odd list - if there's an odd amount of elements, say for example 1, 2, 3 the middle point of 3 - is 1.5 - and if you're iterating through indexes the iterative variable will count the middle point as 1. So it's a bit tricky, not sure what you'd want to do.Consider the following code though - it does exactly what you want, but with odd list sizes, it will just divide by a decimal value
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
int size = numbers.size();
int iterativeHalf = size / 2;
float meanHalf = (float) size / 2;
float lowerMean = 0;
float upperMean = 0;
for (int i = 0; i < size; i++) {
int realRef = i + 1;
Integer value = numbers.get(i);
if (realRef > iterativeHalf) { //Should be calculating upper mean
if (upperMean == 0) { //if lowerMean is just a running total, not divided yet to get the mean
System.out.println("the lower mean for numbers is " + lowerMean + " / " + meanHalf);
lowerMean = (lowerMean) / meanHalf; //add last value + divide to set it to the mean
}
System.out.println("upper mean = " + upperMean + " + " + value + " = " + (upperMean + value));
upperMean = upperMean + value; //keep the upper values up total going
} else {
System.out.println("lower mean = " + lowerMean + " + " + value + " = " + (lowerMean + value));
lowerMean = lowerMean + value; //keep adding the lower halfs values up
}
}
//When it breaks, must divide upperMean by size to get mean
System.out.println("the upper mean for numbers is " + upperMean + " / " + meanHalf);
upperMean = (upperMean) / meanHalf;
System.out.println(" ");
System.out.println("FINAL lower mean = " + lowerMean);
System.out.println("FINAL upper mean = " + upperMean);
Output is:
lower mean = 0.0 + 10 = 10.0
lower mean = 10.0 + 20 = 30.0
the lower mean for numbers is 30.0 / 2.0
upper mean = 0.0 + 30 = 30.0
upper mean = 30.0 + 40 = 70.0
the upper mean for numbers is 70.0 / 2.0
FINAL upper mean = 35.0
FINAL lower mean = 15.0
This, for a [10, 20, 30, 40] will yield the output shown above but essentially (10+20)/2 as the lower mean and (30+40)/2 for the upper mean.
For [10, 20, 30, 40, 50] will yield (10 + 20) / 2.5 the lower mean and (30+40+50)/2.5 for the upper mean
Only take sum of half the array. Give one more element to your second or first half in case if your array size is odd.
public void firstHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts/2;
for (i = 0; i < NrElmts/2; i++) { // take sum only till half.
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half the elements
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
public void secondHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts % 2 == 0 ? NrElmts/2 : NrElmts/2 + 1; // If odd, this second array will contain one more element.
for (i = NrElmts/2; i < NrElmts; i++) { // take sum for the next half
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half elements (half + 1) in case of odd length.
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
Since you already have way to make mean for entire array, all you need to do is find mid position of array and then run from and to that point.
In your example: NrElmts is 10, so divide your NrElmnts by 2, so you can get mean for 1 to 5, and then 6 to 10 both 5 each.
Think about situation where you have odd number of elements in array, how do u want to do it, whether in first array or second. let me know if this need help as well.
Steps:
1) create a new variable say a1 to NrElmts/2, and go with your mean function from 1 to a1
2) go from a1+1 to NrElmnts
Let me know if you need any help.
EDIT: I have edited in the output of the program.
The program calls for estimating a given value mu. User gives a value of mu, and also provides four different numbers not equal to 1 (call them w, x, y, z). The program then attempts to find an estimate of the mu value by using the de Jaeger formula.
If I enter values of 238,900 for mu, and w=14, x=102329, y=1936, z=13
then the value of estimate should be 239,103, and the error about .08%.
My code with the for loops works perfectly fine:
public static void main(String[] args) {
SimpleReader in = new SimpleReader1L();
SimpleWriter out = new SimpleWriter1L();
double bestEstimate = 0; // used to hold the estimate the computer while return
double bestA = 0, bestB = 0, bestC = 0, bestD = 0; // to hold the values of the exponents for each number
double[] exponents = { -5, -4, -3, -2, -1, -1.0 / 2.0, -1.0 / 3.0,
-1.0 / 4.0, 0, 1.0 / 4.0, 1.0 / 3.0, 1.0 / 2.0, 1, 2, 3, 4, 5 };
double[] userNumbers = new double[4];
double mu = getPositiveDouble(in, out);
for (int i = 0; i < 4; i++) {
userNumbers[i] = getPositiveDoubleNotOne(in, out);
}
for (int a = 0; a < exponents.length; a++) {
double a1 = Math.pow(userNumbers[0], exponents[a]);
for (int b = 0; b < exponents.length; b++) {
double b1 = Math.pow(userNumbers[1], exponents[b]);
for (int c = 0; c < exponents.length; c++) {
double c1 = Math.pow(userNumbers[2], exponents[c]);
for (int d = 0; d < exponents.length; d++) {
double d1 = Math.pow(userNumbers[3], exponents[d]);
double currentEstimate = a1 * b1 * c1 * d1;
if (Math.abs(mu - currentEstimate) < Math
.abs(mu - bestEstimate)) {
bestEstimate = currentEstimate;
bestA = exponents[a];
bestB = exponents[b];
bestC = exponents[c];
bestD = exponents[d];
}
}
}
}
}
out.println("Best estimate: " + bestEstimate);
out.println(userNumbers[0] + "^" + bestA + ", " + userNumbers[1] + "^"
+ bestB + ", " + userNumbers[2] + "^" + bestC + ", "
+ userNumbers[3] + "^" + bestD);
out.println("Error: " + calculateError(mu, bestEstimate) * 100 + "%");
}
Output:
Enter a positive real number: 238900
Enter a positive real number that isn't 1: 14
Enter a positive real number that isn't 1: 102329
Enter a positive real number that isn't 1: 1936
Enter a positive real number that isn't 1: 13
Best estimate: 239102.78648033558
14.0^-5.0, 102329.0^1.0, 1936.0^0.5, 13.0^4.0
Error: 0.08488341579555334%
However, with the while loops, I am unable to replicate this.
while (a < exponents.length) {
double a1 = Math.pow(userNumbers[0], exponents[a]);
while (b < exponents.length) {
double b1 = Math.pow(userNumbers[1], exponents[b]);
while (c < exponents.length) {
double c1 = Math.pow(userNumbers[2], exponents[c]);
while (d < exponents.length) {
double d1 = Math.pow(userNumbers[3], exponents[d]);
double currentEstimate = a1 * b1 * c1 * d1;
if (Math.abs(mu - currentEstimate) < Math
.abs(mu - bestEstimate)) {
bestEstimate = currentEstimate;
bestA = exponents[a];
bestB = exponents[b];
bestC = exponents[c];
bestD = exponents[d];
}
d++;
}
c++;
}
b++;
}
a++;
}
Output:
Enter a positive real number: 238900
Enter a positive real number that isn't 1: 14
Enter a positive real number that isn't 1: 102329
Enter a positive real number that isn't 1: 1936
Enter a positive real number that isn't 1: 13
Best estimate: 0.0
14.0^0.0, 102329.0^0.0, 1936.0^0.0, 13.0^0.0
You haven't initialized the variables for the next few iterations.
You need to reinitialize the variables used for while loop's condition check outside their respective while loops. i.e
b = 0;
while(b < exponents.length){
}
Similarly do it for the while loops which use variables c & d.
Daniel's answer is correct : the
structure of the while loop should be:
int a=0, b=0, c=0, d=0;
while (a < length) {
b=0;
while (b < length) {
c=0;
while (c < length) {
d=0;
while (d < length) {
d++;
}
c++;
}
b++;
}
a++;
}
I'm trying to get the overall average of the grades. I was able to get the average of each individual grade. Now just to get the total I'm not sure how to get it.
My output is:
Quizzes:66.0
Labs:88.0
Lab_atendance: 81.0
Midterms:91.0
public static double average(int[] scoreArray, int numScores,
int maxGrade, String name) {
double sum = 0;
for (int i = 0; i < scoreArray.length; i++) {
sum += scoreArray[i];
}
double average = Math.round((sum / numScores)*100/maxGrade);
System.out.println( name + ":" + average+" %");
return average;
}
What you are doing in not average exactly! but still..
Do the same procedure for Quizzes, Labs, Lab_attendance and Midterms! Isn't it obvious?
Here your numScores will be 4!
So from your given input
Avg = ((66.0 + 88.0 + 81.0 + 91.0) / 4) * 100 / maxGrade)
Your average calculation (and method signature) seem incorrect (averages are not calculated by dividing a "max"), I would use something like
// Note the new method signature - name then a variable number of scores.
public static double average(String name, int... scores) {
double sum = 0;
for (int score : scores) { // <-- for each loop.
sum += score;
}
final double average = (scores != null) ? sum / scores.length : 0;
System.out.println(name + ":"
+ Math.round(average * 100) + " %"); //<-- Display as a percentage
return average;
}
So after browsing the already asked questions on here and other sites I figured I would give this a go.
I am working on an exercise that wants you to set up a program in Java that takes an input of 10 numbers and computes the average(mean) and the standard deviation and outputs them.
My problem is that when I run the program, and then enter my desired 10 values and hit enter, nothing happens. For some reason the System printouts that occur after the loop are not being executed. The println inside the loop is not necessary, but is just to show that the values are being calculated correctly as the loop runs, and they are.
I am aiming to have the current value that myValues is assigned to to be added to sum1, and the square of myValues to be added to the sqrdSum. sqrdSum is just a variable I made to sum the squares of the values entered so that the calculation of standard deviation later in the program will be cleaner.
As expected, I am not looking for this to be done for me, just some advice on how to adjust my code such that the printlns at that occur after the loop will execute. I am expecting it to be something to do with my logic, but can not figure it out. Hopefully it is something simple I have managed to miss.
Thanks.
So far I have set it up using a for loop:
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = sum1 / n;
double std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = input1.nextDouble();
for (int count = 0; count <= n; count++) {
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
myValues = input1.nextDouble();
}
System.out.print("The mean of your values is: " + mean1);
System.out.print("The standard deviation of your values is: " + std1);
//Test values: 1 2 3 4.5 5.6 6 7 8 9 10
//Should give a mean of 5.61
//std of 2.99794
The problem is, that input1.nextDouble() blocks until the next number is entered. You are entering 10 numbers, but you expect 11 inputs, since you have this line
double myValues = input1.nextDouble();
which executes once and
myValues = input1.nextDouble();
inside the loop which executes 11 times. Just move it at the beginning of the loop:
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = 0;
for (int count = 0; count < n; count++) {
double myValues = input1.nextDouble();
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
}
As Brian noted, you also have an off-by-one error. You start at 0 but count to 10, that makes 11 loop cycles. Change <= to <
Just change count <= n to count < n in your cycle. You're accidentaly expecting one too many values.
While the answers given did solve your original problem there is also another problem with your code. You won't be getting the correct mean because of how you initiate it and then don't set it to any values after your for loop.
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = sum1 / n;
double std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
The lines above should read,
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = 0.0;
double std1 = 0.0;
and then after your for loop you should calculate mean1 and std1 like the code below.
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = 0.0;
double std1 = 0.0;
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = 0.0;
for (int count = 0; count < n; count++) {
myValues = input1.nextDouble();
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
}
mean1 = sum1 / n;
std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
System.out.print("The mean of your values is: " + mean1);
System.out.print("The standard deviation of your values is: " + std1);
//Test values: 1 2 3 4.5 5.6 6 7 8 9 10
//Should give a mean of 5.61
//std of 2.99794