Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Ron McLeod
• Paul Clapham
• Bear Bibeault
• Junilu Lacar
Sheriffs:
• Jeanne Boyarsky
• Tim Cooke
• Henry Wong
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• salvin francis
• Frits Walraven
Bartenders:
• Scott Selikoff
• Piet Souris
• Carey Brown

# squaring values in a loop

Greenhorn
Posts: 12
• • • • I am trying to write a program which determines the standard deviation of ten user input integers. I have been able to write a formula that is able to sum the numbers. The problem comes when I try to sum the square roots of the numbers. This is hard to describe, but what I am trying to do would look like this, 1^2 + 2^2 + 3^2 + 4^2 = 30. The problem that I am having is that I end up squaring the sum of the numbers...
This is what I have so far; Could anyone help?

lowercase baba Posts: 12893
63   • • • • sum and sum2 are TERRIBLE names. Sum of what? How is sum2 different from sum? The idea is that you give variables names that MEAN something, so that in 2 weeks when you come back to it, it's EASY to know what is what.

now...

It would be of TREMENDOUS help if you posted complete code that compiled and ran. This does not.

Next, I can't see how this would work at all, even to get the sum. It looks to me like your sum would contain twice the total. [edit - nevermind]

Why do you have "sum = sum + data" on line 26? At this point, you know data must be zero, so this is an unnecessary line.

Finally, you get the square of the total because that is exactly what this code says to do:

sum2 = Math.pow(sum, 2);

What you need to do is compute the square of each number as you get it, and add that to your sum2 (and PLEASE choose a better name, like "sumOfSquares").

fred rosenberger
lowercase baba Posts: 12893
63   • • • • also, if you want the user to input exactly 10 values, why do you have a sentinel value? If you want exactly 10 inputs, use a for-loop and quit after 10. If you want to use a sentinel, then don't say "input 10 number"....say "input as many numbers as you want, and enter 0 when you are done"

Peter Haugen
Greenhorn
Posts: 12
• • • • fred rosenberger wrote:

Why do you have "sum = sum + data" on line 26? At this point, you know data must be zero, so this is an unnecessary line.

Finally, you get the square of the total because that is exactly what this code says to do:

sum2 = Math.pow(sum, 2);

What you need to do is compute the square of each number as you get it, and add that to your sum2 (and PLEASE choose a better name, like "sumOfSquares").

I have sum = sum + data because I also need to calculate the mean and by using that I was able to do so. I have been programming for all of three weeks, so please excuse me for not thinking to use a for loop in this problem.

I understand that the code is doing exactly what I am telling it. I also understand that I need to compute the square of each number as you get it, and add that to sumOfSquares (formerly sum2), that is what I was asking about in the original post. What I don't understand is how to do that...

fred rosenberger
lowercase baba Posts: 12893
63   • • • • The best advice is usually this:

Turn off your computer. Get some paper, some pencils, and a very large eraser.

Write down the steps you would take if you had to do this yourself - or better, the steps you would give a 10 year old child if THEY had to do it.

Pretend you are going to ask a person to speak some numbers aloud. Then you need to tell them the mean and the standard deviation. When you are done, you should have a list of steps to follow. Then, you go back and revise it, making each step simpler and simpler. Then you revise it again. And again.

Eventually, you get to the point where each and every step is something you know how to do in Java (or Perl, or Ada, or C++, or whatever language you want.

I also need to calculate the mean and by using that I was able to do so.

This is not the way to program. If you can't tell me why you have it, then it shouldn't be there. "Because it worked" is not a valid reason. If you really think it is necessary, run your code with it. Then, comment it out, re-compile, and run it with the same inputs...you'll get the exact same output.

so please excuse me for not thinking to use a for loop in this problem.

It really doesn't matter what kind of loop you use. For-loops and while loops can both be used pretty much interchangeably. What I was trying to get at was not the technical specifics of which exact java statement you use. Rather, it seems you have not thought out your algorithm before you wrote your code. My guess (and yes, it is a guess), is you started writing code, and wrote the print statement about inputting ten number. Then, later, you wrote the loop to get numbers, and decided to use a sentinel (i.e. a value of 0) to end input. Note that the user has no idea how to stop inputting values. I didn't read all your code (and a user never will) before trying to run it, and I thought it was broken because no matter how many numbers I input, it happily accepted them all and wouldn't stop.

Now, in this block:

you compute the sum of all the numbers, as they are entered. Wouldn't it also be possible to compute the square of the number currently entered, and accumulate the sum of those at the same time?

Peter Haugen
Greenhorn
Posts: 12
• • • • So, I have tried to take your advice about sitting down and writing everything out. This is what I have come up... At this point I am having issues calculating the deviation... Could anyone please help?

import java.util.Scanner;
public class LabEx4_47PH {

public LabEx4_47PH() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

//declare variables
double data = 0, count = -1 ;
double sum = 0;
double sumOfSquares = 0;
double sumOfSquaredIntegers = 0;

//User enters 10 numbers
System.out.println("Enter 10 numbers, when you are finished enter a 0 and press enter: ");
do{
data = input.nextDouble();
sum += data;
sumOfSquaredIntegers += Math.pow(sum, 2);
count++;
sumOfSquares += Math.pow(data,2);

}while (data != 0);

// The numbers that the user enters are summed here.
sum = sum + data;

//The mean is calculated here.
double mean = sum / count;

//This calculates the sum of the squared integers.
sumOfSquares = sumOfSquares + data;

//This calculates the square of the sum of the integers
sumOfSquaredIntegers = Math.pow(sum, 2);

//This calculate the deviation
double deviation1 = Math.sqrt((sumOfSquares -( sumOfSquaredIntegers / data)) / data - 1 );

//Output results
System.out.println("the mean is," + mean);

System.out.print(deviation1);
}

}

Marshal Posts: 25835
69   • • • • Then perhaps your problem is that you read in the numbers that the user inputs, but you don't store them anywhere so that you can go through them a second time to calculate the standard deviation? Peter Haugen
Greenhorn
Posts: 12
• • • • Paul Clapham wrote:Then perhaps your problem is that you read in the numbers that the user inputs, but you don't store them anywhere so that you can go through them a second time to calculate the standard deviation?

Please forgive my lack of knowledge here, but I thought that "data" stored them... So, should I define deviation in my loop? Would that allow the user inputs to go into the formula?

fred rosenberger
lowercase baba Posts: 12893
63   • • • • Peter Haugen wrote:So, I have tried to take your advice about sitting down and writing everything out. This is what I have come up

this is not quite what I meant...I don't think a child would understand this.

I mean you should write down how to do it in English...

Ask the user for a number
write it down
do the above two things ten times
etc.

now...

Please forgive my lack of knowledge here, but I thought that "data" stored them...

your variable data can hold one number at a time. As you loop through, when you get a new value, you no longer have the old one. It's like you erased the old value so you could write in a new one.

If you want to limit the user to no more than ten values, you could use an array. If you want to allow for any number, you could use an ArrayList. As you get each number, you'd store it in the next 'slot' of the collection.

Then, after you have them all, you can loop through it as many times as you like, looking at each value as you go.

Bartender Posts: 10777
71   • • • • Peter Haugen wrote:So, I have tried to take your advice about sitting down and writing everything out. This is what I have come up... At this point I am having issues calculating the deviation... Could anyone please help?

Yes. StopCoding (←click) - which is what Fred was telling you to do politely.

From what I can see, you haven't done that, because all I see is another piece of code.

You need to be able to describe your actions IN ENGLISH - all of them, and in detail - before you write a single line of Java code.

Some questions for you - and answer them in English; not with Java code:
1. What is the formula for standard deviation? Because what you've done doesn't look like it to me (although it has, admittedly, been nearly 40 years since Stats 'A'-Level ). (*)
2. Use enters a 3. What do you do?
3. User enters 17. What do you do now?
4. User enters 26... Hopefully you get the idea.
5. Once the user has entered all their numbers what do you need to do? And answer in detail.

Winston

(*)  - Ah, I get what you're doing now (told you it was a while). You're using the cumulative SD calculation - in which case, it's doubly important that you can explain each step in detail.

Peter Haugen
Greenhorn
Posts: 12
• • • • I got it finally and I did exactly what you guys said. I turned off the computer and sat down with a notebook and pencil. It worked. It can be really hard when you have a million things going on to just sit down and slow down and write out a problem. But, that made a world of difference for me. Thanks everyone for the help with this problem.

Winston Gutkowski
Bartender Posts: 10777
71   • • • • Peter Haugen wrote:Thanks everyone for the help with this problem.

You're most welcome.

And you know what? You've just learned a lesson that some programmers I know still haven't mastered; so don't forget it. If you can continue to do it for everything you write, you'll be well ahead of the game: Think first; code last.

Winston

fred rosenberger
lowercase baba Posts: 12893
63   • • • • That is terrific - glad you got it working.

Now, of course it doesn't HAVE to be pencil/paper. I routinely use my computer. I even use my java editor to do it, but always, my first half dozen passes are in English.

Once I have a pretty good algorithm, I'll cut'n'paste chunks of it as comments into various classes and methods, but the English is always my template. 