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.
Related
I'm supposed to calculate
using Simpson's rule, with 4 sub intervals.
I surely do not want do it by hand so I have tried to write that algorithm in Java.
The formula for Simpson's rule is
And here is my code:
import java.util.Scanner;
import java.util.Locale;
public class Simpson {
public static void main(String[] args) {
Scanner input = new Scanner(System.in).useLocale(Locale.US);
//e= 2.718281828459045 to copy paste
System.out.println("Interval a: ");
double aInt = input.nextDouble();
System.out.println("Interval b: ");
double bInt = input.nextDouble();
System.out.println("How many sub intervals: ");
double teilInt = input.nextDouble();
double intervaldistance = (bInt-aInt)/teilInt;
System.out.println("h = "+"("+bInt+"-"+aInt+") / "+teilInt+ " = "+intervaldistance);
double total = 0;
System.out.println("");
double totalSum=0;
for(double i=0; i<teilInt; i++) {
bInt = aInt+intervaldistance;
printInterval(aInt, bInt);
total = prod1(aInt, bInt);
total = total*prod2(aInt, bInt);
aInt = bInt;
System.out.println(total);
totalSum=totalSum+total;
total=0;
}
System.out.println("");
System.out.println("Result: "+totalSum);
}
static double prod1(double a, double b) { // first product of simpson rule; (b-a) / 6
double res1 = (b-a)/6;
return res1;
}
static double prod2(double a, double b) { // second pproduct of simpson rule
double res2 = Math.log(a)+4*Math.log((a+b)/2)+Math.log(b);
return res2;
}
static void printInterval(double a, double b) {
System.out.println("");
System.out.println("["+a+"; "+b+"]");
}
}
Output for 4 sub intervals:
[1.0; 1.4295704571147612]
0.08130646125926948
[1.4295704571147612; 1.8591409142295223]
0.21241421690076787
[1.8591409142295223; 2.2887113713442835]
0.31257532785558795
[2.2887113713442835; 2.7182818284590446]
0.39368288949073565
Result: 0.9999788955063609
Now If I compare my solution with other online calculators (http://www.emathhelp.net/calculators/calculus-2/simpsons-rule-calculator/?f=ln+%28x%29&a=1&b=e&n=4&steps=on), it differs.. But I don't see why mine should be wrong.
My solution is 0.9999788955063609, online solution is 0.999707944567103
Maybe there is a mistake I made? But I have double checked everything and couldn't find.
You may be accumulating the rounding error by doing b_n = a_{n} + interval many times.
Instead you could be using an inductive approach, where you say a_n = a_0 + n*interval, since this only involves introducing a rounding error once.
I will test with actual numbers to confirm and flesh out the answer in a little bit, but in the meantime you can watch this explanation about accumulation of error from handmade hero
PS. As a bonus, you get to watch an excerpt from handmade hero!
UPDATE: I had a look at your link. While the problem I described above does apply, the difference in precision is small (you'll get the answer 0.9999788955063612 instead). The reason for the discrepancy in your case is that the formula used in your online calculator is a slightly different variant in terms of notation, which treats the interval [a,b] as 2h. In other words, your 4 intervals is equivalent to 8 intervals in their calculation.
If you put 8 rectangles in that webpage you'll get the same result as the (more accurate) number here:
Answer: 0.999978895506362.
See a better explanation of the notation used on that webpage here
I changed your delta calculation to the top to so that you don't calculate the delta over and over again. You were also not applying the right multipliers for the odd and even factors, as well as not applying the right formula for deltaX since it has to be: ((a-b)/n) /3
double deltaX = ((bInt-aInt)/teilInt)/3;
for(int i=0; i<=teilInt; i++) { //changed to <= to include the last interval
bInt = aInt+intervaldistance;
printInterval(aInt, bInt);
total = prod2(aInt, bInt, i+1, teilInt); //added the current interval and n. The interval is +1 to work well with the even and odds
totalSum += total;
aInt = bInt;
System.out.println(total);
}
System.out.println("");
System.out.println("Result: "+ (totalSum*deltaX)); //multiplication with deltaX is now here
To account for the right factor of f(x) i changed the prod2 to:
static double prod2(double a, double b, int interval, double n) {
int multiplier = 1;
if (interval > 0 && interval <= n){
//applying the right multiplier to f(x) given the current interval
multiplier = (interval % 2 == 0) ? 4 : 2;
}
return multiplier * Math.log(a);
}
Now it yields the correct result:
I have an exception in my Java program. When I run this code:
ArrayList<Integer> sum = new ArrayList<Integer>();
sum.add(10);
sum.add(15);
sum.add(20);
int total = 0;
int avg;
for(int i = 0; i < sum.size(); i++)
{
total += sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
}
It prints each ArrayList index element then prints the average, but when I run this code:
for(int i = 0; i<sum.size(); i++)
total = total+sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
It prints the average, but I have not given the bracket of the for loop.
How does the code compare?
Lambda stream method in Java 8 can solve this in a easy way:
int myArray[] = { 1, 2, 3 };
Arrays.stream(myArray).average();
The brackets are use to define block of statement
By default, a loop or a condition only read one statement. A statement could be one line or a block of statement
So here is a line
total=total+sum.get(i);
and here is the block of statement
{
total += sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
}
NOTE : You speak about exception but also said that there is an output in both cases, so I guess your exception is not a Java Exception but just some misunderstanding in this behavior.
EDIT : You should change avg type to accept decimal values and you are going to change a bit the line, the easier is to add a static value of float to convert the value :
float avg = 1.0f * total / sum.size();
Because there is a float here (1.0f), the result will be a float, if you only use integers, the result will be rounded in integer (even if you store it in a float).
From your question, I guess that you are learning Java.
If you are in Java 8, you might use Stream (see link for a better explanation):
The new Stream API allows to transform (map), filter values, etc.
It allows to collect them (see Collectors), regrouping them by key (groupingBy), and in your case to compute a summary statistics.
The example below shows you how to do that using either an IntStream (a Stream tailored for int) or a standard Stream:
IntSummaryStatistics stats = Arrays.asList(10, 15, 20)
.stream()
.mapToInt(Integer::intValue)
.summaryStatistics()
;
// alternative
// IntSummaryStatistics stats2 = Arrays.asList(10, 15, 20)
// .stream()
// .collect(Collectors.summarizingInt(Integer::intValue))
// ;
System.out.println("average: " + stats.getAverage());
System.out.println("count: " + stats.getCount());
System.out.println("sum: " + stats.getSum());
See the javadoc for Collectors.summarizingInt.
In java curly braces are used to group the line of code. In first block of code
ArrayList<Integer> sum = new ArrayList<Integer>();
sum.add(10);
sum.add(15);
sum.add(20);
int total = 0;
int avg;
for(int i = 0; i < sum.size(); i++)
{
total += sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
}
in this code you are adding element to total and same time you are calculating average. Let us see each iteration
iteration 1:
total = 10
avg = 10/3 = 3
iteration 2:
total = 25
avg = 25/3 = 8
iteration 3:
total = 45
avg = 45/3 = 15
But in case of second code block
for(int i = 0; i<sum.size(); i++)
total = total+sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
here code is equivalent to
for(int i = 0; i<sum.size(); i++){
total = total+sum.get(i);
}
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
so in for loop, it calculates total only as
iteration 1: total = 10
iteration 2: total = 15
iteration 2: total = 45
after completion of block value of total is 45
and after block, actual average is calculated as:
avg = 45/3 = 15
In java if we don't provide curly braces to group block of code inside for, if and while by default considered only single line inside the block and execute it repeatedly based on condition.
Exception is according to you Is not achieving the expected behaviour for an average on the elements of the collections.
So, as the earlier answer it boiles down to the Java syntax for working with the Loops/conditions/statements that how we use the { // code
}
By defaults a single line of code statement followed after Loops/conditions does not need to wrap in the braces {}
Here the first snippet uses a block of statement to derive average on each element by collecting it in total and dividing with size of collection.
Whereas, the second snippet does the collection of total for all element at first and then go for finding average.
You need to account for the data precisions when deriving mathematical values like avg and use the appropriate primitive data type.
If you remove the braces, the for loop header refers to the (one) very next statement, so the following two examples are equal:
for(int i=0; i<sum.size(); i++)
total=total+sum.get(i);
avg=total/sum.size();
System.out.println("The Average IS:" + avg);
for(int i=0; i<sum.size(); i++) {
total=total+sum.get(i);
}
avg=total/sum.size();
System.out.println("The Average IS:" + avg);
When you leave the brackets for the loop away, then just the first following line will be part of the loop. That means:
for(int i=0; i<sum.size(); i++)
total=total+sum.get(i);
avg=total/sum.size();
System.out.println("The Average IS:" + avg);
Is equivalent to
for(int i=0; i<sum.size(); i++){
total=total+sum.get(i);
}
avg=total/sum.size();
System.out.println("The Average IS:" + avg);
Same counts also for e.g. if/else.
1st
for(int i = 0; i < sum.size(); i++)
{
total += sum.get(i);
}
2nd
for(int i = 0; i < sum.size(); i++)
total += sum.get(i);
//but in this for loop it considers only one statement as inside for loop
3rd
for(int i = 0; i < sum.size(); i++)
total += sum.get(i);//only this statement is considered as inside the loop
System.out.println("hello");//this statements is not considered inside the loop
1st and 2nd for loops are same
You need to insert bracket in 2nd code of for loop the following.
for(int i = 0; i<sum.size(); i++) {
total = total+sum.get(i);
avg = total / sum.size();
System.out.println("The Average IS:" + avg);
}
Because if you don't insert bracket in for loop, only one line under the for loop will execute for looping process. So you need to make bracket for starting line to ending line that you want to execute in looping process.
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;
I was having some problem when trying to calculate the percentage based on an array list.
int total = 0;
double percentage = 0;
for(int i = 0; i < accountList.size(); i++){
total += Integer.parseInt(accountList.get(i).getTotalCount());
}
for(int j = 0; j < accountList.size(); j++){
percentage = Math.round(Double.parseDouble(accountList.get(j).getTotalCount()) / (double)total);
Log.i("PCT", String.valueOf(percentage));
}
Basically the first loop is to calculate the total. Then as for second loop, I am looping each items in the array list divided by the total to get the percentage.
However, when I try to print out the percentage, I am getting 0.0. But then when I print out the total, it did returned me the total.
Any ideas?
Thanks in advance.
% = Value / Total * 100
So the calculation should be :
percentage = Math.round((Double.parseDouble(accountList.get(j).getTotalCount()) * 100.0) / (double)total);
Most likely all your fractions are less than 0.5 so when you round the faction you keep getting 0.
I suspect you want to print the percentage which is 100 x the faction.
long percentage = Math.round(100.0 *
Double.parseDouble(accountList.get(j).getTotalCount()) / total);
Or
long percentage = 100L*Integer.parseInt(accountList.get(j).getTotalCount()) / total;
Using a integer result might not be ideal. I suggest adding a digit of precision like this.
double percentage = 1000L
* Integer.parseInt(accountList.get(j).getTotalCount())
/ total / 10.0;
By multiplying by 10x what you need for the integer calculation, you get an extra digit of precision when you divide by 10.0.
e.g.
100 * 1 / 3 == 33
1000 * 1 / 3 / 10.0 == 33.3
How do you find an average of a group of random numbers. For example, how would you find the average of, say you prompt the user for how many times they want to generate a random number and they entered 9 and you make the random number with random = randlist.nextInt(100) + 1;? I know you find the average by dividing the sum of the numbers by how many numbers there are, but in this case, how do you find the numbers generated by the random method and add them together and divide them by 9?
With:
double avg = 0.0;
for (int i = 0; i < nTimes; i++) {
avg += randlist.nextInt(100) + 1;
}
avg /= nTimes; //This is the final average