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
};
Related
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.
Can you give me advice about precision of computing Taylor series for an exponent? We have a degree of exponent and a figure of precision calculating as imput data. We should recieve a calculating number with a given precision as output data. I wrote a program, but when I calculate an answer and compare it with embedded function's answer, it has differents. Can you advice me, how I can destroy a difference between answeres? formula of exponent's calculating
#include "stdafx.h"
#include "iostream"
#include <math.h>
#include <Windows.h>
#include <stdlib.h>
using namespace std;
int Factorial(int n);
double Taylor(double x, int q);
int main()
{
double res = 0;
int q = 0;
double number = 0;
cout << "Enter positive number" << "\n";
cin >> number;
cout << "Enter rounding error (precision)" << "\n";
cin >> q;
cout << "\n" << "\n";
res = Taylor(number, q);
cout << "Answer by Taylor : " << res;
cout << "Answer by embedded function: " << exp(number);
Sleep(25000);
return 0;
}
int Factorial(int n) {
int res = 1;
int i = 2;
if (n == 1 || n == 0)
return 1;
else
{
while (i <= n)
{
res *= i;
i++;
}
return res;
}
}
double Taylor(double x, int q) {
double res = 1;
double res1 = 0;
int i =1;
while (i)
{
res += (pow(x, i) / Factorial(i));
if (int(res*pow(10, q)) < (res*pow(10, q)))
{//rounding res below
if ( ( int (res * pow(10,q+1)) - int(res*pow(10, q))) <5 )
res1 = (int(res*pow(10, q))) * pow(10, (-q));
else
res1 = (int(res*pow(10, q))) * pow(10, (-q)) + pow(10,-q);
return res1;
}
i++;
}
}
There are two problems in your code. First, the factorial is very prone to overflow. Actually I dont know when overflow occurs for int factorials, but I remember that eg on usual pocket calculators x! overflows already for x==70. You probably dont need that high factorials, but still it is better to avoid that problem right from the start. If you look at the correction that needs to be added in each step: x^i / i! (maths notation) then you notice that this value is actually much smaller than x^i or i! respectively. Also you can calculate the value easily from the previous one by simply multiplying it by x/i.
Second, I dont understand your calculations for the precision. Maybe it is correct, but to be honest for me it looks too complicated to even try to understand it ;).
Here is how you can get the correct value:
#include <iostream>
#include <cmath>
struct taylor_result {
int iterations;
double value;
taylor_result() : iterations(0),value(0) {}
};
taylor_result taylor(double x,double eps = 1e-8){
taylor_result res;
double accu = 1; // calculate only the correction
// but not its individual terms
while(accu > eps){
res.value += accu;
res.iterations++;
accu *= (x / (res.iterations));
}
return res;
}
int main() {
std::cout << taylor(3.0).value << "\n";
std::cout << exp(3.0) << "\n";
}
Note that I used a struct to return the result, as you should pay attention to the number of iterations needed.
PS: see here for a modified code that lets you use a already calculated result to continue the series for better precision. Imho a nice solution should also provide a way to set a limit for the number of iterations, but this I leave for you to implement ;)
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.
I have this very simple function that checks the value of (N^N-1)^(N-2):
int main() {
// Declare Variables
double n;
double answer;
// Function
cout << "Please enter a double number >= 3: ";
cin >> n;
answer = pow(n,(n-1)*(n-2));
cout << "n to the n-1) to the n-2 for doubles is " << answer << endl;
}
Based on this formula, it is evident it will reach to infinity, but I am curious until what number/value of n would it hit infinity? Using a loop seems extremely inefficient, but that's all I can think of. Basically, creating a loop that says let n be a number between 1 - 100, iterate until n == inf
Is there a more efficient approach to this problem?
I think you are approaching this the wrong way.
Let : F(N) be the function (N^(N-1))(N-2)
Now you actually know whats the largest number that could be stored in a double type variable
is 0x 7ff0 0000 0000 0000 Double Precision
So now you have F(N) = max_double
just solve for X now.
Does this answer your question?
Two things: the first is that (N^(N-1))^(N-2)) can be written as N^((N-1)*(N-2)). So this would remove one pow call making your code faster.
pow(n, (n-1)*(n-2));
The second is that to know what practical limits you hit, testing all N will literally take a fraction of a second, so there really is no reason to find another practical way.
You could compute it by hand knowing variable size limits and all, but testing it is definitely faster. An example for code (C++11, since I use std::isinf):
#include <iostream>
#include <cmath>
#include <iomanip>
int main() {
double N = 1.0, diff = 10.0;
const unsigned digits = 10;
unsigned counter = digits;
while ( true ) {
double X = std::pow( N, (N-1.0) * (N-2.0) );
if ( std::isinf(X) ) {
--counter;
if ( !counter ) {
std::cout << std::setprecision(digits) << N << "\n";
break;
}
N -= diff;
diff /= 10;
}
N += diff;
}
return 0;
}
This example takes less than a millisecond on my computer, and prints 17.28894235
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've written code using class object to calculate the value of e^1 by approximation using the summation of series given below, but seems like i can't get the logic to work properly.I tried running it to 5 terms for approximation but my answer was 1.2 only where it should be around 2.7038...
e^1 is given by the series 1 + 1/1! + 1/2! + 1/3! ...
#include <iostream>
#include <stdlib.h>
using namespace std;
class factorial
{
public:
double loopfactorial ( double y)
{
double value;
for (int a=0; a<=y; a++)
{
value=1;
value = value*a;
}
return value;
}
};
int main()
{
factorial calcu;
int x;
double sum;
cout<<"Enter the number of terms to approximate exponent:"<<endl;
cin>>x;
for (int y=1; y<=x-1; y++)
{
int n = calcu.loopfactorial(y);
sum=1.0;
sum = sum + 1/n;
}
cout<<"The value of e is "<<sum<<endl;
return 0;
}
For reference and the benefit of future readers, here's the "correct" code:
#include <iostream>
#include <cstdlib>
int main()
{
unsigned int terms;
if (!(std::cout << "Number of terms: " && std::cin >> terms))
{
std::cout << "Error, I did not understand you.\n";
return EXIT_FAILURE;
}
double e = terms > 0 ? 1.0 : 0.0, term = 1.0;
for (unsigned int n = 1; n < terms; ++n)
{
term /= n;
e += term; // this is "e += 1/n!"
}
std::cout << "e is approximately " << e << "\n";
}
(The code can be trivially extended to compute ex for any x.)
You should move the variable initializations out of the loops - you're resetting them over and over.
Side note: it's rather pointless to put loopfactorial in a class.
I found three problems with your code, both are similar to each other
1. in loopfactorial(), value=1 should be defined before the loop body
2. in main(), sum=1.0 should be defined before the loop body
3. in loopfactorial(), loop variable a should have been initialized with either 1 or 2 instead of 0.
Try moving your initial values outside the loop:
#include <iostream>
#include <stdlib.h>
using namespace std;
class factorial
{
public:
double loopfactorial ( double y)
{
double value;
// MOVED INITIAL VALUE HERE
value=1;
for (int a=1; a<=y; a++)
{
value = value*a;
}
return value;
}
};
int main()
{
factorial calcu;
int x;
double sum;
cout<<"Enter the number of terms to approximate exponent:"<<endl;
cin>>x;
// MOVED INITIAL VALUE HERE
sum=1.0;
for (int y=1; y<=x-1; y++)
{
int n = calcu.loopfactorial(y);
sum = sum + 1/n;
}
cout<<"The value of e is "<<sum<<endl;
return 0;
}