Using pow() gives errors - c++

Please have a look at the following code
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
//int side1 = 0;
//int side2 = 0;
//int rightSide = 0;
cout << "Right Side" << setw(10) << "Side1" << setw(10) << "Side2" << endl;
for(int i=1;i<=500;i++)
{
//side1++;
//cout << side1 << endl;
for(int a=1;a<=500;a++)
{
//side2++;
//cout << "side 2 " << side2 << endl;
for(int c=1;c<=500;c++)
{
//rightSide++;
int rightSideSqr = pow(c,c);
int side1Sqr = pow(i,i);
int side2Sqr = pow(a,a);
if(rightSideSqr == (side1Sqr+side2Sqr))
{
cout << rightSideSqr << setw(15) << i << setw(10) << a << endl;
}
}
}
}
}
This gives an error "PythagorialTriples.cpp:28: error: call of overloaded `pow(int&, int&)' is ambiguous". This doesn't happen if I simply used manual power like i*i, instead of the method. Can someone please explain me why this is happening? I am new to C++ anyway. Thanks

There are multiple overloads for pow defined in <cmath>. In your code, these 3 are all equally valid, therefore the compiler is having trouble choosing the right one:
pow(float, int);
pow(double, int);
pow(long double, int);
The simplest solution is to use static_cast on the first argument, to remove any ambiguity. e.g.
int side1Sqr = pow( static_cast<double>(i) ,i );
int side2Sqr = pow( static_cast<double>(a) ,a );

Whoa! Pow(x,y) is x raised to the yth power (in mathematical terms - xy)!! NOT x*y
So you're trying to take iith power in a 5003 nested loop. Probably not what you want. Replace with pow(i,2) for your desired behavior.
Note, #Mooing Duck raises an excellent point about x^y in c++ which is the XOR operator. But I think you sort of figured that out if you're already using pow anyway.

It cannot figure out which overloaded function to use.
Try
pow(double(i), i);
or
pow(double(i), 2);
Since that looks like what you want.

Are you sure that you can handle such a big pow?
Pow(x,y) is xy. Look at the
http://www.cplusplus.com/reference/clibrary/cmath/pow/
double pow ( double base, double exponent );
long double pow ( long double base, long double exponent );
float pow ( float base, float exponent );
double pow ( double base, int exponent );
long double pow ( long double base, int exponent );
There is no INT version. Your compiler didnt know which one is correct. You have to tell them by using static_cast like:
int side1Sqr = pow(static_cast<double>i,i);
for big precision calculate you can use:
http://gmplib.org/
There is also one solution from boost.

Related

How ceil function works in c++?

When I execute this code the value of ans1, ans2 is 50002896 and 50005000.
I know there is some issues with ceil function but was not able to figure out the exact cause.
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long ans1 = 0, ans2 = 0;
for (long long i = 1; i <= 10000; i++)
{
ans1 = ans1 + ceil((float)i / 1);
ans2 = ans2 + i;
}
cout << ans1 << " " << ans2 << endl;
}
The source of the problem is not the ceil function, but rather that not all integers can be represented accuratly as floating point values.
Some more info about floating point representation: Wikipedia IEEE 754. And a related post: Which is the first integer that an IEEE 754 float is incapable of representing exactly?.
The following code is a minimal demonstration of the same issue that causes your issue:
float f1 = 100000000;
f1++;
std::cout << std::to_string(f1) << std::endl;
[Wrong] Output (expected: +1):
100000000.000000
One approach would be to use double instead of float.
This will not solve the principle issue, but will make the range of representable integers a lot bigger:
double f1 = 100000000;
f1++;
std::cout << std::to_string(f1) << std::endl;
Output:
100000001.000000
Some side notes:
better to avoid #include <bits/stdc++.h> - see here: Why should I not #include <bits/stdc++.h>?.
better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
First, try to use specific headers like #include , in this case, .because #include <bits/stdc++.h> will bring lots of junk.
So the issue is with float not ceil explained below
floating-point values do not represent exact values.
Code:-
#include <iostream>
#include <iomanip>
using namespace std;
// Driver Code
int main()
{
float num1 = 10000.29;
float num2 = 10000.2;
// Output should be 0.0900000000
cout << std::setprecision(15)
<< (num1 - num2);
return 0;
}
Output :-
0.08984375

Precision problem with multiplying float values C++

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
setlocale(LC_ALL, "RU");
float P_a2, P_b2,result2,x,y,z;
cout << "P_a(x)= 9,09*x^9– 9,09*x^3+ 9,09*x\n";
cout << "P_b(x)= – 8980,032*x^6– 186,34*x^4– 649,23*x^2\n\n";
x = 1.2;
cout << "\n";
y = x * x * x * x * x * x;
P_a2 = ((9.09 * y - 9.09) * x * x + 9.09) * x;
cout << setprecision(9) << P_a2 << "\n\n";
z = x * x;
P_b2 = ((-8980.032 * z - 186.34) * z - 649.23) * z;
cout << setprecision(9) << P_b2 << "\n\n";
result2 = P_a2 * P_b2;
cout <<fixed<< setprecision(15) << result2 << "\n\n"; //prints -1184587.00000000
//right answer is -1 184 586,9806370984
}
Is this problem related with type of the value?
I really cant understand why it happens and what should i do...
Can somebody please explain why does it happens with result2 and can i avoid it without changing the type?
P.S my bad, i've forgot to add the minus, right answer ofc is
-1 184 586,9806370984
P.P.S yes, i know that this code can be optimized, but our teacher said us to do so.
And yes parentheses are correct.
I know i can fix it by using double, i'm just asking if i can solve this problem without using it
There are two issues (not c++ issues, more of general floating point numerical calculation issues):
float type is usually 6-7 decimal digits precision, using double would give you 15-16 decimal digits, more helpful for the problem. Seems like you need more digits than float to at least hold the result.
There is a subtraction in P_a, so should watch for catastrophic cancellation when grouping the terms.

Percentage calculation returns zero [duplicate]

This question already has answers here:
Why does dividing two int not yield the right value when assigned to double?
(10 answers)
Closed 4 years ago.
double calculatePercentage(int unmatched, int charLen){
double percentageReturn = (((charLen - unmatched)/charLen) * 100);
cout << "percenpercentageReturntage " << percentageReturn << endl;
return percentageReturn;
}
I tried to calculate percentage of these values, but it returns 0. I tried with int, float and double but all returns 0.
Can anyone help me with this ?
You may typecast double while doing division and multiplication operation so that as a whole result will be in double. You may do something like this:
double percentageReturn = ( ( (double)(charLen - unmatched) / (double)charLen ) * 100.0 );
In the below statement, the right hand side of the assignment is evaluated first and then assigned to percentageReturn at which point the implicit conversion (if required) takes place.
double percentageReturn = (((charLen - unmatched)/charLen) * 100);
In the right hand side, all parameters are integers, so it will be integer division followed by the truncation of the result.
Since (charLen - unmatched) will be less than charLen, the truncated result will be 0.
To fix this, you can either cast the numerator or the denominator of the division to double and this will give you division without truncation.
(double)(charLen - unmatched) or (double)charLen.
The division operator / in C++, performs an integer division when its both sides are of integral type. To overcome this, you need to cast arguments to a floating-point type first, as follows:
double cl = static_cast<double>(charLen);
double um = static_cast<double>(unmatched);
Note that if you're using Modern C++, it's a good practice to do cast the implicitly convertible types with static_cast, instead of old C-style casts.
To solve your issue please try one of this two possible solution
#include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;
double calculatePercentage(int unmatched, int charLen) {
double percentageReturn = (((double)(charLen - unmatched) / (double)charLen) *
100);
cout << "percenpercentageReturntage_int " << percentageReturn << endl;
return percentageReturn;
}
double calculatePercentage(double unmatched, double charLen) {
double percentageReturn = (((charLen - unmatched) / charLen) * 100);
cout << "percenpercentageReturntage_double " << percentageReturn << endl;
return percentageReturn;
}
int main()
{
cout << "the integer function value is :" << calculatePercentage(4, 50) << endl;
cout << "the double function value is :" << calculatePercentage((double)4,
(double)50) << endl;
return 0;
}

define double constant as hexadecimal?

I would like to have the closest number below 1.0 as a floating point. By reading wikipedia's article on IEEE-754 I have managed to find out that the binary representation for 1.0 is 3FF0000000000000, so the closest double value is actually 0x3FEFFFFFFFFFFFFF.
The only way I know of to initialize a double with this binary data is this:
double a;
*((unsigned*)(&a) + 1) = 0x3FEFFFFF;
*((unsigned*)(&a) + 0) = 0xFFFFFFFF;
Which is rather cumbersome to use.
Is there any better way to define this double number, if possible as a constant?
Hexadecimal float and double literals do exist.
The syntax is 0x1.(mantissa)p(exponent in decimal)
In your case the syntax would be
double x = 0x1.fffffffffffffp-1
It's not safe, but something like:
double a;
*(reinterpret_cast<uint64_t *>(&a)) = 0x3FEFFFFFFFFFFFFFL;
However, this relies on a particular endianness of floating-point numbers on your system, so don't do this!
Instead, just put DBL_EPSILON in <cfloat> (or as pointed out in another answer, std::numeric_limits<double>::epsilon()) to good use.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main()
{
double const x = 1.0 - numeric_limits< double >::epsilon();
cout
<< setprecision( numeric_limits< double >::digits10 + 1 ) << fixed << x
<< endl;
}
If you make a bit_cast and use fixed-width integer types, it can be done safely:
template <typename R, typename T>
R bit_cast(const T& pValue)
{
// static assert R and T are POD types
// reinterpret_cast is implementation defined,
// but likely does what you expect
return reinterpret_cast<const R&>(pValue);
}
const uint64_t target = 0x3FEFFFFFFFFFFFFFL;
double result = bit_cast<double>(target);
Though you can probably just subtract epsilon from it.
It's a little archaic, but you can use a union.
Assuming a long long and a double are both 8 bytes long on your system:
typedef union { long long a; double b } my_union;
int main()
{
my_union c;
c.b = 1.0;
c.a--;
std::cout << "Double value is " << c.b << std::endl;
std::cout << "Long long value is " << c.a << std::endl;
}
Here you don't need to know ahead of time what the bit representation of 1.0 is.
This 0x1.fffffffffffffp-1 syntax is great, but only in C99 or C++17.
But there is a workaround, no (pointer-)casting, no UB/IB, just simple math.
double x = (double)0x1fffffffffffff / (1LL << 53);
If I need a Pi, and Pi(double) is 0x1.921fb54442d18p1 in hex, just write
const double PI = (double)0x1921fb54442d18 / (1LL << 51);
If your constant has large or small exponent, you could use the function exp2 instead of the shift, but exp2 is C99/C++11 ... Use pow for rescue!
Rather than all the bit juggling, the most direct solution is to use nextafter() from math.h. Thus:
#include <math.h>
double a = nextafter(1.0, 0.0);
Read this as: the next floating-point value after 1.0 in the direction of 0.0; an almost direct encoding of "the closest number below 1.0" from the original question.
https://godbolt.org/z/MTY4v4exz
typedef union { long long a; double b; } my_union;
int main()
{
my_union c;
c.b = 1.0;
c.a--;
std::cout << "Double value is " << c.b << std::endl;
std::cout << "Long long value is " << c.a << std::endl;
}

Check double variable if it contains an integer, and not floating point

What I mean is the following:
double d1 =555;
double d2=55.343
I want to be able to tell that d1 is an integer while d2 is not. Is there an easy way to do it in c/c++?
Use std::modf:
double intpart;
modf(value, &intpart) == 0.0
Don't convert to int! The number 1.0e+300 is an integer too you know.
Edit: As Pete Kirkham points out, passing 0 as the second argument is not guaranteed by the standard to work, requiring the use of a dummy variable and, unfortunately, making the code a lot less elegant.
Assuming a c99 and IEEE-754 compliant environment,
(trunc(x) == x)
is another solution, and will (on most platforms) have slightly better performance than modf because it needs only to produce the integer part. Both are completely acceptable.
Note that trunc produces a double-precision result, so you don't need to worry about out of range type conversions as you would with (int)x.
Edit: as #pavon points out in a comment, you may need to add another check, depending on whether or not you care about infinity, and what result you want to get if x is infinite.
Assuming you have the cmath <math.h> library, you can check the number against it's floor. If the number might be negative, make sure you get the absolute first.
bool double_is_int(double trouble) {
double absolute = abs( trouble );
return absolute == floor(absolute);
}
avakar was almost right - use modf, but the detail was off.
modf returns the fractional part, so the test should be that the result of modf is 0.0.
modf takes two arguments, the second of which should be a pointer of the same type as the first argument. Passing NULL or 0 causes a segmentation fault in the g++ runtime. The standard does not specify that passing 0 is safe; it might be that it happens to work on avakar's machine but don't do it.
You could also use fmod(a,b) which calculates the a modulo b passing 1.0. This also should give the fractional part.
#include<cmath>
#include<iostream>
int main ()
{
double d1 = 555;
double d2 = 55.343;
double int_part1;
double int_part2;
using namespace std;
cout << boolalpha;
cout << d1 << " " << modf ( d1, &int_part1 ) << endl;
cout << d1 << " " << ( modf ( d1, &int_part1 ) == 0.0 ) << endl;
cout << d2 << " " << modf ( d2, &int_part2 ) << endl;
cout << d1 << " " << ( modf ( d2, &int_part2 ) == 0.0 ) << endl;
cout << d2 << " " << modf ( d2, &int_part2 ) << endl;
cout << d1 << " " << ( modf ( d2, &int_part2 ) == 0.0 ) << endl;
cout << d1 << " " << fmod ( d1, 1.0 ) << endl;
cout << d1 << " " << ( fmod ( d1, 1.0 ) == 0 ) << endl;
cout << d2 << " " << fmod ( d2, 1.0 ) << endl;
cout << d2 << " " << ( fmod ( d2, 1.0 ) == 0 ) << endl;
cout.flush();
modf ( d1, 0 ); // segfault
}
int iHaveNoFraction(double d){
return d == trunc(d);
}
Now, it wouldn't be C if it didn't have about 40 years of language revisions...
In C, == returns int but in C++ it returns bool. At least on my Linux distro (Ubuntu) you need to either declare double trunc(double); or you could compile with -std=c99, or declare the level macro, all in order to get <math.h> to declare it.
How about
if (abs(d1 - (round(d1))) < 0.000000001) {
printf "Integer\n"; /* Can not use "==" since we are concerned about precision */
}
Fixed up to work using rounding to reflect bug Anna found
Alternate solutions:
if ((d1 - floor(d1) < 0.000000001) || (d1 - floor(d1) > 0.9999999999)) {
/* Better store floor value in a temp variable to speed up */
printf "Integer\n"; /* Can not use "==" since we are concerned about precision */
}
Theres also another one with taking floor, subtracting 0.5 and taking abs() of that and comparing to 0.499999999 but I figure it won't be a major performance improvement.
Just compare ceil and floor value of d
return floor(d)==ceil(d);
So, for d1=555, the above statement will return 555==555, i.e, true, so it's an integer.
And for d2=555.6, the above statement will return 555==556, i.e, false, so it's a double.
How about this?
if ((d1 - (int)d1) == 0)
// integer
#define _EPSILON_ 0.000001
bool close_to_int(double &d)
{
double integer,
fraction = modf(d, &integer);
if(fraction < _EPSILON_)
{
d = integer;
return true;
}
if((1.0 - fraction) < _EPSILON_)
{
d = integer + 1;
return true;
}
return false;
}
This looks at both side of the integer value and sets the value of d if it is within the limits of an integer value.
try:
bool isInteger(double d, double delta)
{
double absd = abs(d);
if( absd - floor(absd) > 0.5 )
return (ceil(absd) - absd) < delta;
return (d - floor(absd)) < delta;
}
#include <math.h>
#include <limits>
int main()
{
double x, y, n;
x = SOME_VAL;
y = modf( x, &n ); // splits a floating-point value into fractional and integer parts
if ( abs(y) < std::numeric_limits<double>::epsilon() )
{
// no floating part
}
}
In many calculations you know that your floating point results will have a small numerical error that can result from a number of multiplications.
So what you may really want to find is the question is this number within say 1e-5 of an integer value. In that case I think this works better:
bool isInteger( double value )
{
double flr = floor( value + 1e-5 );
double diff = value - flr;
return diff < 1e-5;
}
I faced a similar questions.
As I needed to round the double anyway, that's what I find working:
double d = 2.000000001;
int i = std::round(d);
std::fabs(d-i) < 10 * std::numeric_limits<double>::epsilon()
modf uses std::nearbyint(num) that why you should use nearbyint which return a double without decimal and may be faster.
#include <iostream>
#include <cmath>
int main() {
double number = 55.12;
if (!(number - std::nearbyint(number))) {
std::cout << "Is integer!";
} else {
std::cout << "Has decimal!";
}
return 0;
}
A sample code snipped that does it:
if ( ABS( ((int) d1) - (d1)) )< 0.000000001)
cout <<"Integer" << endl;
else
cout <<"Flaot" << endl;
EDIT: Changed it to reflect correct code.
Below you have the code for testing d1 and d2 keeping it very simple. The only thing you have to test is whether the variable value is equal to the same value converted to an int type. If this is not the case then it is not an integer.
#include<iostream>
using namespace std;
int main()
{
void checkType(double x);
double d1 = 555;
double d2 = 55.343;
checkType(d1);
checkType(d2);
system("Pause");
return 0;
}
void checkType(double x)
{
if(x != (int)x)
{
cout<< x << " is not an integer "<< endl;
}
else
{
cout << x << " is an integer " << endl;
}
};