Averaging the values in while loop [duplicate] - java

This question already has answers here:
Why doesn't my "While Loop" print the computation of finding the average "score"?
(5 answers)
Closed 7 years ago.
So I have a public accessor method called gettSeconds and I have called it in a while loop as below 20 times:
int i =0;
double sum = 0;
double average =0;
while (i < 20) {
call.read();
sum = sum + call.getSeconds();
System.out.println(sum);
average = sum / 10.0;
}
So basically I called read 20 times and then I calculate how long it took to read the file each time and average the total time.But I keep getting my last time as my average instead of the actual average.

I am enticed to change much more - but lets keep as much as possible of your original - you probably want to do something like this?
double sum = 0;
double average =0;
for (int i=0; i < 20; i++) {
call.read();
sum = sum + call.getSeconds();
}
average = sum / 20.0;
System.out.println(average);
Note that for your original while (i < 20) - the condition is always true, so in effect it would run forever. Maybe you had different intentions - in that case, please be more clear.

You should be calculating the average after summing all the values:
int i = 0;
int sum = 0;
int average = 0;
while (i < 20) {
call.read();
sum = sum + call.getSeconds();
}
average = sum / 20.0;
We can simplify this by using a for loop and the += operator:
int sum = 0;
for (int i = 0; i < 20; i++) {
sum += call.read().getSeconds();
}
int average = sum / 20.0;

Related

Use processing solve: S=1+1/2-1/3+1/4...+1/99-1/100 [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
I want to solve this math question in processing:
S=1+1/2-1/3+1/4...+1/99-1/100.
Here is my code (don't know why it doesn't work. I suppose it will print one number in the console, but it comes out a series of natural numbers):
float N = 0;
float T = 0;
int i = 1;
void draw() {
for (i = 1; i < 100; i += 2) {
N = N + 1 / i;
T = T + 1 / (i + 1);
}
println(N - T);
}
First off, draw() runs every frame. Use setup() instead, it runs once.
Second, dividing ints results in an int. Go ahead, do println(1/i) and see the magic.
Third, always google around for some time before going to SO. You'll learn more by finding it out yourself. And this was very solvable with google and a little effort ;)
working code:
float N = 0;
float T = 0;
int i = 1;
void setup() {
for (i = 1; i < 100; i += 2) {
N = N + 1.0 / i;
T = T + 1.0 / (i + 1);
}
println(N - T);
}
1 / i is a division expression between two integers, the result of which will be an int obtained by truncating the fraction part of the result. Since you are calculating float you can resolve it by using a 1f float literal
for (int i = 1; i < 100; i += 2) {
N = N + 1f / i;
T = T + 1f / (i + 1);
}
However your code currently counts the following:
Consider i = 1 for which you get T = 0.5 which you later subtract from N while you should be adding it as per your problem statement. One way to sole it is to write the code as:
float sum = 1;
for (int i = 2; i <= 100; i++) {
float term = 1f / i;
if (i % 2 != 0) {
term *= -1;
}
sum += term;
}
System.out.println(sum);

finding the sum of the sreies, using java

the question is to find the sum of this series
series
i used this code to solve it , but im not quite sure the logic is correct.
the noofterms is how many terms are going to be added
and x is the number that will be assigned to the variable.
does the logic seem correct?
public static double sumOfSeries(double x, int noofterms){
double evennumbers=1;
double oddnumbers=1;
double result=1;
// since the power of x starts from 1 , we start i from 1 and increment by 2
for (int i=1; i<noofterms; i+=2 ){
// we reset starting numbers so we start from them everytime
evennumbers = 1;
oddnumbers = 1;
// everytime the number increases by 2 when it is smaller than i+1
// ex when its equal to 2 , j = 3 , j+1 = 4 so it increments by 2
// when its 4 , j = 5 , j+ 1 = 6 , it increments
for (int j=2; j<=i+1; j+=2){
// multiply by increments of 2
evennumbers= evennumbers * j;
}
// it starts from 1 and increments by 2 so it goes like 1,3,5
for (int z=1; z<=i; z+=2){
oddnumbers = oddnumbers * z;
}
result*=((Math.pow(x, (double)i)) / (double)i) + (oddnumbers/evennumbers);
}
return result;
}
You can do it better. Note that numerators and denominators form two sequences, so you can keep previous terms to efficiently make computations, this will look like this :
long even = 1;
long odd = 1;
double result = x;
for(long i = 1; i < noofterms; i++)
{
even *= 2 * i;
odd *= 2 * i - 1;
double oper = Math.pow(x, (double)(2 * i + 1)) / (double)(2 * i + 1);
result += (double)even / (double)odd * oper;
}
You can improve by using logarithms because even and odd will grow very fast and will lead to overflows :
double even = 0.0;
double odd = 0.0;
double result = x;
double logx = Math.log(x);
for(long i = 1; i < noofterms; i++)
{
even += Math.log((double)(2 * i));
odd += Math.log((double)(2 * i - 1));
double oper = logx * (2 * i + 1) - Math.log((double)(2 * i + 1));
result += Math.exp(even - odd + oper);
}
EDIT: only one sequence could also be computed : p *= (double)(2*i)/(2*i-1). Then the log trick is not useful.

Calculating Average After Parsing Integers

This is for Java.
I just finished parsing each column from String to int. However, now I am having a tough time figuring out how to calculate each column and finding the average.
For example, this is what I have after I parsed each column:
int Q1 = Integer.parseInt(columns[1]);
This is what I tried to find the average, but was unsuccessful.
int Q1s = Q1;
int i;
int total = 0;
for (i = 0; i < 6; i++) {
total = total + Q1s;
}
double avg = total / Q1s;
return avg;
I know how to find the average the normal way (Example: int Q1[] = {1,2,3};)
But it is not the same for parsing an array of integers.
Any hints on how to proceed would be greatly appreciated!
P.S. I don't want the answer...I just want a direction on where to go from here. That is why I didn't put the complete code that I currently have.
Your logic to calculate total is wrong. You are not adding all the elements, what you're doing is adding the first element n times.
Assuming Q1 is your array of Strings.
for(int i = 0; i < Q1.length; ++i)
{
total += Integer.parseInt(Q1[i]);//this is what you want to do. Parse it here
}
double avg = (double) total / Q1.length;
two things:
1) you should use:
double avg = total / <ColumnCount>;
2) you need to casting, So
double avg = ((double)total) / <ColumnCount>;
double avg = total / Q1s;
Calculating average is wrong here. It should be
double avg = total / 6;
It should be divided by the total number of elements here you are
using 6 as a constant.

String not printing out after conclusion of loop

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

Sum of factorials

So I need to output a sum of factorials like 1!+2!...+n!=sum I found a way to get a single factorial but I don't know how to sum them together. This is my attempt at doing so:
System.out.println("Ievadiet ciparu");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Ciparam jabut pozitivam.");
else
{
while (x>2){
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
sum=sum+fact;
n=n-1;
if (n==0) break;
}
System.out.println("Faktorialu summa "+sum);
Rather than have a loop 1-n and calculate each factorial elsewhere, I would accumulate the sum as you calculate the factorials - ie have two local variables; one for factorial and one for the sum:
long factorial = 1, sum = 0;
for (int i = 1; i <= n; i++) {
factorial *= i;
sum += factorial;
}
When tested with n = 5, sum is 153, which is correct: 1 + 2 + 6 + 24 + 120
Your problem was that the sum was outside the loop - you just needed braces like here.
Also, your while loop condition x < 2 will never change, so either the loop will never execute (if x > 1) or the loop will never terminate, because x is not changed within the loop.
hmmm my search for finding a recursive(via recursive method calling) version of these code still getting nowhere
`public static long factorialSum(long n){
long x = n;
for(int i = 1; i < n; i++){
x = (n-i)*(1+x);
}
return x;
}`
if you just look at the problem more closely you'll see you can do it in linear time, the trick is in (n-1)! + n! = (n-1)!*(1 + n), to understand this more deeply i recommend add (n-2)! just to see how it grows.

Categories

Resources