I'm trying to calculate the pi using Monte Carlo Method. But I always get zero, I don't know why.
Here's my code
#include <tchar.h>
#include <Windows.h>
#include <omp.h>
#include <iostream>
#include<math.h>
using namespace std;
int main(int argc, char *argv[]){
int N = 1000, n = 0;
double x = 0, y = 0;
double answer;
for (int i = 0; i < N; i++){
x = (double)rand() / (double)RAND_MAX;
y = (double)rand() / (double)RAND_MAX;
if (((x*x) + (y*y)) < 1)
++n;
}
//cout << "n = " <<n << endl;
answer = n / N;
cout << answer*4.0 << endl;
//system("pause");
}
Integer division in the answer calculation:
answer = n / N;
'nuff said.
Edit 1:
It's Friday, so I'll add some explanation.
The variables n and N are declared as integers.
The division takes precedence over any conversions or assignments. The division is performed as two integers, then the fractional portion is truncated. The remaining value is converted to double then assigned to the variable answer.
Please, please, don't differentiate identifiers by case. The n and N should be different letters. This helps the writer and reviewer refrain from typo defects.
Related
Sorry if this is summarized wrong and etc.. This is my first time asking a question on Stackoverflow, so if I'm making any mistakes, let me know.
Problem:
In line 20, code embedded below, I'm performing a calculation, more specifically this calculation: 11 * 50 / 100, which if I'm not mistaken should give a result of 5.5. But my console gives me a result of 5. Maybe it's because it's late, but I personally can't see a thing wrong in that line.
Or let me know if I'm using cout wrong.
Explanation of program:
You receive an input of five ages, a ticket cost 10, which results in 50. But you may substract the youngest persons age as percent from the final price.
Kind regards Olle!
using namespace std;
int main() {
int ages[5] = {11,18,19,30,34};
int ticketPrice = 10;
/*for (int i = 0; i < 5; ++i) {
cin >> ages[i];
}*/
int agesSize = *(&ages + 1) - ages;
int finalPriceWithoutDiscount = ticketPrice * agesSize;
int min;
min = ages[0];
for(int i=0;i< agesSize; i++){
if(ages[i] < min ){
min = ages[i];
}
}
double discount= min * finalPriceWithoutDiscount / 100;
cout << discount << endl;
// expected output from values:[min=11, fPWD = 50]
// 5.5
// actual output:
// 5.00000
double truePrice = finalPriceWithoutDiscount - discount;
cout << std::fixed << truePrice;
// my output:
// 45.00000
return 0;
}
In your calculation of discount, all operands (min, finalPriceWithoutDiscount and 100) are of type int. The operations performed are therefore integer operations. No decimals are produced.
The (integral) result of the calculation is then assigned to a floating point variable, and thus converted to floating point. But that happens after the computation has been performed in the integer domain.
To fix this problem, cast at least one of your operands to double. Or rather, since you’re using a literal (100), use a floating point literal:
double discount = min * finalPriceWithoutDiscount / 100.0;
This causes the operation involving 100.0 (that is, the division) to be performed on floating point numbers instead of integers.
The other answer actually answers your question, but I thought I'd contribute a more C++ example:
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
int main() {
std::vector<int> ages{11, 18, 19, 30, 34};
int ticketPrice = 10;
/*for (int i = 0; i < 5; ++i) {
cin >> ages[i];
}*/
int finalPriceWithoutDiscount = ticketPrice * ages.size();
int min = *std::min_element(ages.begin(), ages.end());
// Fix the calculation by using a double, 100.0
double discount = min * finalPriceWithoutDiscount / 100.0;
std::cout << discount << '\n';
// Fix by casting to double
double truePrice = static_cast<double>(finalPriceWithoutDiscount) - discount;
std::cout << std::fixed << truePrice;
return 0;
}
I am struggling to make this equation equals to each other because of a bad understanding of mathematics.
The problem is that the equation does not equal to each other
here is my code for better understand
#include <iostream>
#include <ccomplex>
using std::cout;
int main() {
int n = 8;
double sum = 0.0;
unsigned long long fact =1;
for (int i = 1; i <= n; i++)
{
fact *= 2*i*(2*i-1);
sum += 1.0 / fact;
}
std::cout << "first equation " << sum << std::endl;
double e = M_E;
double st = 1.0/2.0*(e + (1.0/e));
std::cout <<"second equation " << st << std::endl;
return 0;
}
the output
first equation 0.543081
second equation 1.54308
The result it nearly It must be at least equal before the comma,
You don't account for n = 0, which yields 0! and thus 1. Therefore, you need to add 1 to sum.
So..
Here is the code:
#include <iostream>
#include <limits>
#include <math.h>
using namespace std;
int main()
{
unsigned long long i,y,n,x=45;
unsigned long long factorial = 1;
for(n = 0; n <= 5; n++)
{
y = (pow(-1,n)*pow(x,2*n)) / factorial;
cout << "COS IS " << y << endl;
}
for(int i = 1; i <=n; i++)
{
factorial *= 2*i;
}
}
I get an overflow but I really don't know why. I use unsigned long long just to make sure that I on't get but.. I still get it. Even limited to small numbers. I tried to implement this:
https://en.wikibooks.org/wiki/Trigonometry/Power_Series_for_Cosine_and_Sine
But I really can't do it because of the overflow. Do you have any ideea on what can I do ? I am newbie in programming so, take it easy on me :D
There are many issues.
you use integer types when you should use floating point types
you use unsigned types for signed calculations
you don't use radians but degrees (45° ≈ 0.78539 radians)
you don't calculate the factorial in the loop, it is always 1, you only calculate it at the end of the loop but then it's too late, and your calculation of the factorial is wrong anyway.
the algorithm is wrong, it just doesn't do what Maclaurin's therorem says, you need to sum up the terms, but you just print the terms.
You probably want this:
#include <iostream>
#include <cmath>
using namespace std;
long factorial(int n)
{
long result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return result;
}
int main()
{
double x = 0.785398163397448309616; //PI/4 expectd result COS(PI/4) = 0.7071067
double mycosinus = 0;
for (int n = 0; n <= 5; n++)
{
mycosinus += (pow(-1, n) * pow(x, 2 * n)) / factorial(2*n);
cout << "COS IS " << mycosinus << endl;
}
}
This is your wrong algorithm for calculating the factorial of 5:
int main()
{
int n = 5;
int factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= 2 * i;
}
cout << "factorial 5 = " << factorial << endl;
}
The calculated value is 3840 instead of 120. I let you find out what's wrong yourself.
For performing this sort of maths you need to use a floating point like float or double not integral types like long, int or long long, given that sin and cos can both return negative numbers you shouldn't be using unsigned either.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have this line in my code (ll is long long int):
ll d = (x / ( (y / 1000000) - 1) );
which seems to be causing this floating point exception error.
However when I change it to:
ll d = (1000000*x)/(y-1000000);
the error disappears. Simple algebra will lead you to believe that they both are one and the same thing.
Here is the full code, which is for UVa problem 10660, Grocery Store. https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=643&page=show_problem&problem=2177
//Problem Link: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=643&page=show_problem&problem=2177
//Problem type: Complete Search
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <stdio.h>
#include <queue>
#include <set>
#include <cmath>
#include <assert.h>
#include <bitset>
#include <map>
#include <unordered_map>
#include <iomanip> //cout << setprecision(n) << fixed << num
typedef long long int ll;
using namespace std;
int main() {
//freopen("output.out", "w", stdout);
int cnt = 0;
for (int a = 1; a*4 <= 2000; a++) {
for (int b = a; a+3*b <= 2000; b++) {
for (int c = b; a+b+2*c <= 2000; c++) {
ll x = a+b+c;
ll y = a*b*c;
if (y <= 1000000) continue;
//ll d = (x / ( (y / 1000000) - 1) );
ll d = (1000000*x)/(y-1000000);
if (d < c || x + d > 2000) continue;
if ( abs( (x + d) / 100.0 - ( y * d) / 100000000.0) < 1e-8 ) {
cout << setprecision(2) << fixed << a/100.0 << " " << b/100.0 << " " << c/100.0 << " " << d/100.0 << endl;
cnt++;
}
}
}
}
cout << cnt << endl;
return 0;
}
If I change it to ll d = (x / ( (y / 1000000.0f) - 1) ) however, then the error disappears, but I get a Wrong Answer, and the number of lines in the output is only 717, whereas it should be 949 (I had to google the answer to figure out this weird issue :/)
First, there is no floating-point arithmetic going on here: everything is done in integers (specifically, long long ints).
This means that when y is between 1000000 and 1999999, inclusive, the result of the division y / 1000000 is going to be 1. Hence, subtracting 1 from it would lead to zero denominator, and a division by zero exception.
Your second expression will produce the same result only when y is equal to 1000000, but the program is going to crash with the same exception.
The trick to solving problems of this kind is keeping numerator and denominator separate, and performing your math entirely in integers, i.e. without floating point numbers. Constructing a simple class for representing rational numbers should help simplifying your code.
The numeric code is a bit flag of exactly what error you hit (8 means division by zero).
These are the other bits:
enum {
XCP_INVALID=0,
XCP_OVERFLOW,
XCP_UNDERFLOW,
XCP_DIV_BY_ZERO,
XCP_INEXACT,
XCP_NXCP
};
I am to calculate the arithmetic mean, the geometric mean, and the harmonic mean for five numbers using a single while loop.
Here is what I have so far:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
float a;
float g;
float h;
sum1 = 0;
sum2 = 0;
sum3 = 0;
n = 5;
int k;
int main()
{
printf("Please Enter Five Integers:\n");
while (k = 0 && k < n && ++k);
{
scanf("%lf", &k);
sum1 = sum1 + k;
sum2 = sum2 * k;
sum3 = sum3 + (1.0 / k);
}
a = sum1 / n;
g = pow(sum2, 1 / n);
h = n / sum3;
printf("Arithmetic mean: %.3f\n", a);
printf("Geometric mean: %.3f\n", g);
printf("Harmonic mean: %.3f\n", h);
return 0;
Your C program has several issues.
You don't declare all the variables you are using, for example, and there's no need for them to be global.
Your initial value for sum2 (0) is wrong, it will never update because you repetedly multiply k times 0.
Then in pow(..., 1 / n) the 1/n is an integer division, so you are elevating to 0.
Your loop and its condition must be modified. Try this, I used double, instead of integers and float, but it depends on your assignment:
#include <stdio.h>
#include <math.h>
#define MAX 80
int main()
{
double a, g, h, k;
double sum = 0, prod = 1, sum_inv = 0;
const int n = 5;
int i = 0;
printf("Please, enter five numbers:\n");
char buffer[MAX];
while ( i < n ) {
fgets(buffer, MAX, stdin);
if ( sscanf(buffer, "%lf", &k) != 1 ) {
printf("Wrong format, floating point number expected\n");
continue;
}
if ( k == 0.0 ) {
printf("You should enter non zero numbers\n");
continue;
}
++i;
sum += k;
prod *= k;
sum_inv += (1.0 / k);
}
a = sum / n;
g = pow(prod, 1.0 / n);
h = n / sum_inv;
printf("Arithmetic mean: %.3f\n", a);
printf("Geometric mean: %.3f\n", g);
printf("Harmonic mean: %.3f\n", h);
return 0;
}
Apologies if this is brutal, but simply saying there are multiple issues and proceeding to correct them without explaining why they are issues or what was done to correct them doesn't make for a very good answer. It makes for homework cut-and-paste.
#define _CRT_SECURE_NO_WARNINGS
This is actually a bad idea. Those security warnings often tell you you're taking unnecessary risks. They are annoying, but often they are right.
#include <stdio.h>
#include <math.h>
These should be <cstdio> and <cmath>. Better still, don't use cstdio. Use the C++ equivalents.
float a;
float g;
float h;
sum1 = 0;
sum2 = 0;
sum3 = 0;
n = 5;
The preceding 4 variables do not have data types. All variables must have a type.
Further initializing sum2 to zero when it will be used to gather a product is a bad idea. 0 will result.
int k;
None of these variables need to be global and all of the variable names are non-descriptive. In a program this size, that's not horrible, but in a large program with dozens or thousands of variables, being able to read from the variable name what it does and what it contains is worth it's weight in gold.
int main()
{
printf("Please Enter Five Integers:\n");
while (k = 0 && k < n && ++k);
The ; is a bad mistake here. ; ends the instruction. It separates the loop from it's body, so you get a while the loops but does nothing else.
But let's look at the loop conditions shall we?
k = 0
this is the same as
k = 0
if (k)
Which is always false since k is 0. This exits the loop right here.
k < n
Which it always is because of k = 0. k is 0. A moot point because this never gets tested.
++k
is always true because at this point k will always be 1.
This screams read the textbook more closely because you missed quite a bit.
{
scanf("%lf", &k);
This line reads a floating point number into an integer. Not a good idea. The results will be bizarre at best.
In addition, the return code from scanf is untested so you have no way to tell whether or not scanf successfully read a value.
And this question is tagged C++. Why use C?
sum1 = sum1 + k;
sum2 = sum2 * k;
sum3 = sum3 + (1.0 / k);
That all looks good to me, other than being really bad, non-descriptive names.
}
a = sum1 / n;
Syntactically and logically sound.
g = pow(sum2, 1 / n);
1 / n will be performed entirely in integer arithmetic and certainly result in a fraction. Integers can't do fractions, so this will result in 0. Any number to the power of 0 is one.
h = n / sum3;
Looks good.
printf("Arithmetic mean: %.3f\n", a);
printf("Geometric mean: %.3f\n", g);
printf("Harmonic mean: %.3f\n", h);
Again, using C in C++. printf has it's uses, even in C++, and frankly this is one of those cases where I might use it (but with caution because there is a performance hit) because the C++ equivalent std::cout << "Arithmetic mean: " << std::fixed << std::setprecision(3) << a << '\n'; is brutally verbose.
return 0;
}
Revising this for C++
#include <cmath>
#include <iostream>
#include <iomanip>
#include <limits>
int main()
{
// discarded a, g, and h. Renamed the rest for easier reading
float sum = 0;
float product = 1;
float invSum = 0;
constexpr int MAX = 5;
int input;
std::cout <<"Please Enter Five Integers:" << std::endl;
int count = 0;
while (count < MAX)
{
if (std::cin >> input)
{ // read a good, or at least not horrible, number
// this will not handle the problem of "123abc" as input. "123" will be
// accepted and "abc" will be seen as a second token and rejected.
// proper handling of this is a question unto itself and has been asked
// hundreds of times.
sum += input;
product *= input;
invSum += (1.0 / input);
count++;
}
else
{ // clean up and ask for new input
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout <<"Bogus integer. Input again: " << std::endl;
}
}
std::cout << "Arithmetic mean: " << std::fixed << std::setprecision(3) << sum / MAX << '\n';
std::cout << "Geometric mean: " << std::fixed << std::setprecision(3) << pow(product, (1.0 / MAX)) << '\n';
std::cout << "Harmonic mean: " << std::fixed << std::setprecision(3) << MAX / invSum << '\n';
return 0;
}