Standard Deviation c++ Formula advice - c++

I have this assignment in which i will show the prompt for it:
Write a program that reads in a set of test score data from the user. (Test
scores should be entered in decimal form to represent the percentage grade). Once the user has
finished entering the test scores (entering -1 will signal the end of input), print out the number of
tests entered, the average of the tests, and the standard deviation. Use the following formula
(Welford’s method) to calculate the standard deviation:
(Standard Deviaton Formula)
You can compute this quantity by keeping track of the count (number of tests), the sum, and the sum
of squares as you process the input values.
Note: Although there are other ways to calculate the standard deviation, please use this method. This
method is used since it only requires one pass of the data. Do not use arrays or vectors.
Now the code below is what I have so far. In the terminal, I'm getting wrong numbers for the average and Std. Deviation outputs (Terminal Output). Is there anything wrong with my math? Any help is appreciated. EDIT: Here is the data I'm using and the expected results I should be getting:
1. 67.8
2. 95.6
3. 89.5
4. 76.7
5. 71.3
6. 83.2
7. 90.6
8. 56.1
9. 98.6
10. 85.2
result:
Number of Test Scores: 10
Average : 81.46
Std. Deviation: 13.39
Code
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double sum = 0;
double sumSq = 0;
double grade = 0;
int numtests = 0;
cout << "Enter the test scores. Once finished, enter -1 to end input.\n";
cin >> grade;
while (grade != -1)
{
cin >> grade;
sum = sum + grade;
sumSq = sumSq + pow(grade, 2);
numtests++;
}
double average = (sum / numtests);
double std = (sumSq - numtests * pow(average, 2) / (numtests - 1));
cout << "The number of scores: " << numtests << "\n";
cout << "Average: " << average << "\n";
cout << "Std. Deviation: " << std << "\n";
return 0;
}

You've written the function so "-1" is part of the calculation which isn't what you want. I could fix it for you, but I think you can take it from that hint. And now that I look again, the first number is NOT part of your calculation.

Related

Usage of arrays to generate random numbers

I'm trying to generate N random floats between 0 and 1 where N is specified by the user. Then I need to find the mean and the variance of the generated numbers. Struggling with finding the variance.
Already tried using variables instead of an array but have changed my code to allow for arrays instead.
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;
int main(){
int N, i;
float random_numbers[i], sum, mean, variance, r;
cout << "Enter an N value" << endl;
cin >> N;
sum = 0;
variance = 0;
for (i = 0; i < N; i++) {
srand(i + 1);
random_numbers[i] = ((float) rand() / float(RAND_MAX));
sum += random_numbers[i];
cout << random_numbers[i] << endl;
mean= sum / N;
variance += pow(random_numbers[i]-mean,2);
}
variance = variance / N;
cout << " The sum of random numbers is " << sum << endl;
cout << " The mean is " << mean << endl;
cout << " The variance is " << variance << endl;
}
The mean and sum is currently correct however the variance is not.
The mean you calculate inside the loop is a "running-mean", ie for each new incoming number you calculate the mean up to this point. For the variance however your forumla is incorrect. This:
variance += pow(random_numbers[i]-mean,2);
would be correct if mean was the final value, but as it is the running mean the result for variance is incorrect. You basically have two options. Either you use the correct formula (search for "variance single pass algorithm" or "running variance") or you first calculate the mean and then set up a second loop to calculate the variance (for this case your formula is correct).
Note that the single pass algorithm for variance is numerically not as stable as using two loops, so if you can afford it memory and performance-wise you should prefer the algorithm using two passes.
PS: there are other issues with your code, but I concentrated on your main question.
The mean that you use inside the variance computation is only the mean of the first to i element. You should compute the mean of the sample first, then do another loop to compute the variance.
Enjoy

How to reset values in for loop?

I need help figuring out where my code went wrong. I want to reset the values for the loop so that it isn't compiling because my output right now is using past input values in current calculation whereas I want the output to be different every time as though it is the firs time running the code. The code works fine when I don't use the while loop, but then I have to rerun the program each time. I want the output to prompt a new input every time, but not use past inputs in the new calculations. I know I'm not explaining it very well, but I'm just sort of lost. Anything helps!
This is my problem:
An approximate value of pi can be calculated using the series given
below:
pi = 4 · [ 1 – 1/3 + 1/5 – 1/7 + 1/9 ... + (–1 ^ n)/(2n + 1) ]
Write a C++ program to calculate the approximate value of pi using
this series. The program takes an input n that determines the number
of terms in the approximation of the value of pi and outputs the
approximation. Include a loop that allows the user to repeat this
calculation for new values n until the user says she or he wants to
end the program.
#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
int n;
double sum=0;
cout << "Enter the number of terms to approximate (or zero to quit):\n";
cin >> n;
if (n == 0)
{
return 0;
}
while (n != 0)
{
{ for(int i=0;i<n;i++)
{
if (i%2==0)
{
sum += 1.0/(2*i+1);
}
else
{
sum += -1.0/(2*i+1);
}
}
cout.setf(ios::showpoint);
cout.precision(3);
cout << "The approximation is " << sum*4 << " using " << n << " terms." << endl;
}
cout << "Enter the number of terms to approximate (or zero to quit):\n";
cin >> n;
}
return 0;
}
This is my output:
This is what the output should be:
You do not reset sum before entering the for loop. Just add
sum=0;
before the for line.
Notice that 2.67 = 6.67 - 4.00.
You want your program to compute a sum for several values of n.
The sum must be initialized to 0 at the beginning of each calculation, inside the while loop.
Actually, it should even be declared there.
C++ doesn't require you to define variables at the start of a function, so it is perfectly legal to write:
while (n != 0)
{
double sum = 0.0;
this would solve your problem. Alternatively, if you want to keep the declaration of sum at the top of the function, just change your code to
while (n != 0)
{
sum = 0.0;

c++ currency converter trailing zeroes

i just started programming and wrote a currency converter programme that needs to be accurate to 2 decimals (using double) However i would not like trailing zeroes but users should still be able to input decimals with set precision rounding it off to a whole integer
Here is the code:
#include <iostream>
#include <iomanip>
using namespace std;
const double DOLLAR = 0.05917;
const double EUROS = 0.05681;
int main()
{
double rand;
double equivD;
double equivE;
cout << setprecision(2)<<fixed;
cout << " Enter Rand amount: ";
cin >> rand;
cout << rand << " Rand(s)= ";
equivD= (rand*DOLLAR);
cout << equivD<< " Dollar(s)\n ";
cout << rand << " Rand(s)= ";
equivE= (rand*EUROS);
cout << equivE<< " Euro(s)\n ";
return 0;
}
Output if entered value is a 1000 is:
1000.00= 57.24 Dollars
1000.00= answer
If an integer is inputed without decimals I would like to remove the .00 but still keep it as a double in case a decimal is inputed. How do I do this?
Don't use floating point for money: you'll be off on the 15th significant figure; which, by the time you've consumed two digits for the cents, is not particularly large.
In your case, use a 64 bit integral type and work in cents, tweaking your formatting when you want to display computed values. (Don't forget to round correctly when using the FX rates).
If you want different formatting for different cases, I would test to see if there is a decimal.
In your example, with doubles, this could be
if( 0 == (((long long)(rand*100)) % 100) )
cout << setprecision(0);
This multiplies rand by 100, converts it to an integral type, and then checks if the right two digits are both zero.
The Better Solution
Use an integral type (like int or long long) to store the value as "hundredths of rands" (like Bathsheba suggested). This reduces rounding errors. To test for the decimal and output, just use a modulo, like this:
cout << (rand / 100); // Integer division
if( 0 != (rand % 100) ) // Are there any amounts less than one rand?
cout << '.' << (rand % 100);
Of course, there is still the issue of reading in the user input to a long long, but I'm not an expert with cin.

Having garbage numbers while calculating percentage

So, I hate to ask, but, I'm having some issue with this, I'm new to C++ and I'm just starting out. Everything is done for the most part. Expect for a little thing.
Line 35-36 should be calculating the average (Which for some reason, I haven't been able to get it to work.)
Line 41-47 should print out the percentage that heads/tails was landed on with precision to one decimal, and then print out the correct numbers of * to represent the percentage.
But, when I run it, my heads/tail count is messed up. As well as my percentage numbers. I'm just looking for a push in the right direction.
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <iomanip>
using std::cout; using std::cin; using std::endl;
using std::fixed; using std::setprecision;
int main()
{
srand(time(0));
int userInput,
toss,
headsCount,
tailsCount;
double headsPercent = 0,
tailsPercent = 0;
cout << "How many times do you want to toss the coin? ";
cin >> userInput;
while(userInput < 0)
{
cout << "Please enter a positive number: ";
cin >> userInput;
}
for(int i = 1; i < userInput; i++)
{
toss = rand() % 2;
if(toss == 0)
headsCount++;
else
tailsCount++;
}
headsPercent = userInput / headsCount * 100;
tailsPercent = userInput / tailsCount;
cout << "Heads: " << headsCount << endl
<< "Tails: " << tailsCount << endl << endl;
cout << "Heads Percentage: " << fixed << setprecision(1) << headsPercent << " ";
for(int b = 0; b < headsPercent; b++)
cout << "*";
cout << "\nTails Percentage: " << tailsPercent << " ";
for(int b = 0; b < tailsPercent; b++)
cout << "*";
return 0;
}
In addition to the uninitialized variables here, that others have pointed out, the calculations are all wrong.
Take out paper and pencil, and run some your own calculations the old-fashioned way.
Let's say there were five tosses, three heads, two tails. This means that (after fixing the uninitialized variables):
userInput=5
headsCount=3
tailsCount=2
Now, here's how you're calculating your supposed percentages:
headsPercent = userInput / headsCount * 100;
tailsPercent = userInput / tailsCount;
So, using your own numbers, you will get:
headsPercent = 5 / 3 * 100
tailsPercent = 5 / 2;
Does this look right to you? Of course not. You can do the arithmetic yourself. Divide 5 by 3 and multiply by 100. This is integer division, so five divided by three is 1, multiplied by 100 is 100. Five divided by two is two. So you get 100% and 2% here.
Of course, that's wrong. Two and three times, out of five, is 40% and 60%, respectively.
Writing a program means:
A) Figure out how calculations need to be made
B) Write the code to do the calculations.
You're still on step A. You need to figure out how you want to make these calculations so they're correct, first.
This has nothing really to do with C++. If you were using any other language, and coded this, in that manner, you'll get the same wrong answers.
The only thing this might have to do with C++ is that integer division, in C++ does not produce a fractional amount. It's integer division. But that's not your only problem.
Firstly u have to correct ur basics of mathematics.
Calculating %age means
example
(Marks obtained)/(Total marks)*100
Not (Total marks/marks obt)*100
Dividing any no by 0 is not defined. So if ur current code randomly assign toss or head =0, then obviously u will have errors.
Secondly talking about codes, U should either initialize i from 0 , or u should use
for (i=1; i<=userInput; i++)
As otherwise the head+toss value will be userInput-1.
Also remember to initialise variables like
Int headsCount=0;
etc. As the variable will take any random value if not initialised to a fixed no. (Though it does not creates a problem here)
And just change the datatype
int userInput,
toss,
headsCount,
tailsCount;
To
double userInput,
toss,
headsCount,
tailsCount;
This will solve your problem.
Advice: Please use
using namespace std;
in the starting of ur programs as u have to type a lot of std::
Welcome to C++. You need to initialise your variables. Your compiler should have warned you that you were using a variable without initialising it. When you don't initialise a value, your program has undefined behaviour.
I'm talking about headsCount and tailsCount. Something like this should be fine:
int headsCount = 0, tailsCount = 0;
Also note that your loop should start at 0, not 1, since you are using the < operator on the final condition.
Finally, your percentage calculations are backwards. It should be:
headsPercent = headsCount * 100 / userInput;
tailsPercent = tailsCount * 100 / userInput;
Now, there's a weird thing that might happen because you are using integer division. That is, your percentages might not add up to 100. What's happening here is integer truncation. Note that I dealt with some of this implicitly using the 100x scale first.
Or, since the percentages themselves are double, you can force the calculation to be double by casting one of the operands, thus avoiding integer truncation:
headsPercent = static_cast<double>(headsCount) / userInput * 100;
In fact, since the only two possibilities are heads and tails, you only need to count one of them. Then you can do:
tailsPercent = 100 - headsPercent;
1) This loop should start from 0:
for(int i = 1; i < userInput; i++)
2) The divisions are not correct:
//headsPercent = userInput / headsCount * 100;
//tailsPercent = userInput / tailsCount;
headsPercent = headsCount / userInput * 100;
tailsPercent = tailsCount / userInput * 100;
3) Finally:
cout << "\nTails Percentage: " << fixed << setprecision(1) << tailsPercent << " ";

double multiplication is getting rounded, and i don't know how to fix it

My code is rounding my double values off, I'm multiplying two doubles, and it's roudning it off to an integer value. can someone help?
cout << "This program will determine the water needs for "
"a refugee camp based on the number of refugees, "
"daily water needs, and the existing water supplies."
<< endl
<< "Please enter the number of refugees: " << endl;
double NumOfRefugees = 0;
cin >> NumOfRefugees;
cout << "Please enter the daily water needs for each person "
"(in the range 7.5 to 15.0 liters per day.): " << endl;
double DailyNeedsPerPerson = 0;
cin >> DailyNeedsPerPerson;
if (DailyNeedsPerPerson < 7.5 || DailyNeedsPerPerson > 15.0)
{
cout << "The entered value is not within a reasonable range as specified in "
"the Sphere Project Humanitarian Charter. The program will now end.";
return 1;
}
double TotalDailyDemand = NumOfRefugees * DailyNeedsPerPerson;
cout << "The total demand is " << TotalDailyDemand << endl;
For example, when I input 15934 and 9.25, My code outputs:
This program will determine the water needs for a refugee camp based on the number of refugees, daily water needs, and the existing water supplies.
Please enter the number of refugees:
15934
Please enter the daily water needs for each person (in the range 7.5 to 15.0 liters per day.):
9.25
147390
The total demand is 147390
Please help!
What you are seeing is a result of the default precision of the output stream being 6 digits.
So, you need to apply some formatting to the output stream to be able to see more than the default 6 digits. For instance:
#include <iostream>
int main()
{
double x = 15934.0;
double y = 9.25;
double z = x*y;
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout.precision(2);
std::cout << z;
}
Output
147389.50
The call to setf is used to specify fixed floating point formatting with a specified number of digits after the decimal point. The call to precision specifies how many digits after the decimal point.
I'm not sure what formatting you actually want because you did not say. But these functions, and the relatives, should allow you to get the result that you desire.