Function pow() int C++ [closed] - c++

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 have a problem when I try to multiply integer 3 pow(67, 1). It return 200 instead 201. Here is my code in C:
int x = 3;
x = x * pow(67, 1);
printf("%d\n", x);
-> 200
Can anyone explain for me. Thanks!

Tentative explanation: the pow function, being performed in double precision, does not "understand" that a power of 1 means "return the exact number" and returns 66.9999. (Lots of 9's but not exactly 67). The multiplication by 3 gives something like 200.99997. Finally since the result is assigned to an int, this is rounded down (truncated) to 200.

pow(67,1) should not compile as C++03, but as Tony observes in a comment, 1C++11's §26.8/11 makes it valid again in C++11. Visual C++ 12.0 rejects the code as C++, evidently playing by C++03 rules. However, the g++ compiler version 4.8.2 accepts the code. With Visual C++ one gets a diagnostic about ambiguous call, since there are many overloads.
In C or in C++11 the arguments are converted to double and pow performs the exponentiation. Although these numbers can be represented exactly as double, the exponentiation operation is not guaranteed to produce an exact integer. E.g. it might be performed as an = en*ln(a).
The result can therefore be slightly more or less than exact 67.
The multiplication expression converts integer 3 to double, exactly, and the multiplication is performed as double. If the pow result is less than 67 then you get a result like 200.9999999..., if it's exact than you get 201.0, and if it's slightly more then you get something like 201.0000001....
Finally the assignment back to x converts that back down to nearest int value, which in the first case is 200, and in the second and third case is 201.
2I can only conclude that the claimed result 200 must (most probably) be incorrect; that it's incorrectly reported.
1)C++11 §26.8/11: “Moreover, there shall be additional overloads sufficient to ensure: 1. If any argument corresponding to a double parameter has type long double, then all arguments corresponding to double parameters are effectively cast to long double. 2. Otherwise, if any argument corresponding to a double parameter has type double or an integer type, then all arguments corresponding to double parameters are effectively cast to double. 3. Otherwise, all arguments corresponding to double parameters are effectively cast to float.”.
2)See commentary for the deleted text.

Related

Comparisons involving literals safe? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Consider the code:
#define LITERAL 1.0
int main()
{
double x = LITERAL;
if (x == LITERAL) return 1;
else return 0;
}
Is this guaranteed to return 1 for any numerical double value we set LITERAL (not just 1.0 but any other double literal)?
EDIT: Why was the question closed because of "missing details"? It is a well defined C/C++ question and got a very good answer. There are no more details required, it is a general question about how these languages work.
First, you have to assume an implementation that's (attempting to be) conforming to Annex F, since otherwise all bets are off; without Annex F (IEEE floating point) C allows all floating point results to be arbitrarily bogus.
Then, according to the language spec, depending on your C implementation's definition of FLT_EVAL_METHOD, yes or no.
If the value is 0 or 1, then yes. The literal is interpreted as double, and the double object stores that value faithfully, and the equality operator yields 1 (true), reflecting that.
If the value is 2, then only if the literal is the eact decimal representation of a representable double or is expressed with sufficient precision that it differs from one only past the precision of long double. Otherwise (for example if it's something like 0.1), since the literal is interpreted with excess precision in long double format the initialization/assignment to a double object truncates the precision to the nominal double precision. Then the equality comparison is guaranteed to result in 0 (false). You can see this in action on Compiler Explorer (note: remove the volatile and you can see it optimized to return a constant 0).
To make matters more complicated, GCC does this wrong by default unless you use -std=c.. or -fexcess-precision=standard, and always does it wrong in C++ mode, and clang/LLVM always do it wrong. So on a target with excess precision (32-bit x86 or m68k, the only real-world-relevant targets with FLT_EVAL_METHOD not 0 or 1) horrible things happen. For a peek into how bad they get, see GCC issue 93806 and (recursively) all of the "See Also" related issues.
So for practical purposes, yes, for everything but 32-bit x86 and m68k, and in a correct C implementation no (but maybe yes, because your compiler is probably broken) for them.

Cannot initialize integer [closed]

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 4 years ago.
Improve this question
I have a method loading:
-(void)loading:(MKTileOverlayPath)path ... {
...
Within this method I am trying to calculate something
NSInteger *a = pow(2, path.z) - path.y - 1;
I get an error:
Initializing 'NSInteger *' (aka 'long *') with an expression of incompatible type 'double'
Why is that double? path.z and path.y are, as stated in the documentation MKTileOverlayPath, integer. And pow(2, path.z) cannot result in an float or double neither, when there are only integers... Why is that?
You have two errors:
The standard C pow() produces a double and it's parameters are also double - your integer arguments are implicitly cast for you. There is no version for integer types. The best solution is not to use casts to get an integer value, that introduces the possibility of errors doe to the nature of floating-point math, but to simply write your own integer power function. You can copy the one in this answer - just implement it using the integer type (int, long etc.) you require.
You have confused your variable type, object types are reference types and declared as pointers, e.g. NSString *; simple numeric types are value types and are not pointers, e.g. NSInteger.
Mathematically it won't result in a non-integer value, but that's not the contract for the pow() function. According to http://www.cplusplus.com/reference/cmath/pow/, the parameters are being implicitly cast to doubles and the return value of the function is always a double.

C++ long long to string conversion fails [closed]

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 5 years ago.
Improve this question
I have the following function which has to convert numbers of any size to strings:
string NumberToString(long long number) {
ostringstream NumberInStream;
NumberInStream.str("");
NumberInStream.clear();
NumberInStream << setprecision(0);
NumberInStream << fixed << number;
return NumberInStream.str();
}
The function works very well for numbers of maxlength: 9.
So for example when I input a 10-digit long number, e.g. 1234567890 it returns wrong format.
Some examples:
1494978929 became 1494978944
1494979474 became 1494979456
1494979487 became 1494979456
1494979498 became 1494979456
1494979500 became 1494979456
1494979529 became 1494979584
1494979540 became 1494979584
However,
2 became 2
120 became 120
44567 became 44567
456.45 became 456 because of setprecision(0)
Welcome to floating point precision. Try your same script using double in the function prototype instead and you will see that you get the results you want. However this will fail if you input integers of a certain length.
Just looks at the output of this . .
printf ("%f\n", 1494978929.f)
And you'll see that you cannot represent that int as a float with total precision. Call the same with .0 instead of .f at the end and you'll see a different result.
This is a problem with IEEE floating point notation: https://en.wikipedia.org/wiki/IEEE_floating_point. Your question says you are converting between a long long, but your function takes a float as an argument. Floats are stored in 32 bits in memory. Depending on implementation, the bits are split into three sets: one bit is used to determine the sign (s), then a number of bits are used for the significand (c), and the rest of the bits are the quotient (q). Depending on the bits set, the number determined using this notation is (-1)^s * c * b^q where b is the base (usually 2 or 10). How all of this is represented depends on your compiler and the ISO standard. What this means is that the numbers represented by IEEE floating point have to fit this function. Basically all of the relatively small integers you would want to represent work with this formula, but when you try to represent very small or very large numbers, IEEE floating point will break down. In your situation, some strings of numbers over 10 digits require too much precision for floats to represent. I recommend that you use a double or long double for these, or use a long long as mentioned above instead of floating point numbers.
yep, float is 32 bit, and part of that is the exponent, so float has less precision than a normal int, but it has a wide range of expression due to sacrificing some bits for the exponent.
either use double, giving you more range, but still not enough for a long long, or make it a template:
template <typename T>
string NumberToString(T number) {
ostringstream NumberInStream;
NumberInStream.str("");
NumberInStream.clear();
NumberInStream << setprecision(0);
NumberInStream << fixed << number;
return NumberInStream.str();
}
That might need some tweaking now though, but it won't lost precision due to passing your value into a data type like float or double that has less bits of precision than the number you started with.

INT vs FLOOR in Fortran

According to gfortran documentation, INT(x) and FLOOR(x) both take input x and convert x to integer type. FLOOR apparently only allows input of type REAL whereas INT takes input of type INTEGER, REAL, and complex.
Is the allowed input type the only difference between INT and FLOOR? If so, can anyone explain why FLOOR exists since it is apparently superfluous?
The "Similar Questions" box showed similar Stack Overflow questions in C, C++, and Python3, but apparently no one has asked this question for Fortran yet, which led me to getting this deep into asking it.
Including Fortran in my quick searches on Google and Stack Overflow meant nothing useful appeared. So this is admittedly a duplicate (unless Fortran has INT and FLOOR quirks separating it from C/C++/Python) but I think it will have utility in allowing the result to be more easily/quickly searchable.
The definition of INT is such that it rounds towards zero for REAL input, while FLOOR always rounds down. Consequently, for negative input, the results differ.
Unlike some of the other languages you reference, the result of calling FLOOR in Fortran is of type INTEGER.
Consider FLOOR in the context of its cousins NINT and CEILING.

Typecasting in C++: why use (type) expression instead of type (expression) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
In python, type casting is done as:
float(a) if the variable a is, say an integer and needs to be converted to float.
Now consider the following C++ code:
int a=5;
int b=10;
cout<< (float) a/b<<endl;
cout<<static_cast<float> (a/b)<<endl;
cout<<static_cast<float> (a)/b;
which gives the output:
0.5
0
0.5
In the first type cast, a is type casted to float explicitly, and then b is type casted implicitly. The final answer is of the type float.
In the second and third type cast, depending on the position of the () either a is first explicitly converted to float, then b implicitly converted and then then the final value is 0.5 or a/b is first calculated as an int, and then type casted to float, making the final value 0.
There is no ambiguity while using static_cast<type>(expr)
My question being:
Wouldn't this be a lot clearer if the first line was written like:
cout<<float(a)/b<<endl;
Eliminating any ambiguity regarding in which order the type casting will be done?
C++ has no restrictions on doing just that, and yet it isn't common practice. Rather, cout<<(int)a/b<<endl; is the prevelant form, which seems to be more ambiguous.
Why is this the case?
Another way to frame this question would be: what advantage does the (type) expression offer over type (expression)?
The main advantage of (type)a over type(a) is that the first works for any type and the second doesn't. Try the following and you will elicit compiler errors;
unsigned long x = unsigned long(3.0);
unsigned long *y = unsigned long *(0);
Beyond that, your question is based on a completely false premise. Contrary to your description, there is no ambiguity in the meaning of any of the expressions you describe.
(float) a/b;
static_cast<float> (a/b);
static_cast<float> (a)/b;
because the second has different meaning from the other two. float)a/b and static_cast<float>(a)/b both convert a to float before performing the division. static_cast<float>(a/b) do the division and then converts the result to float.
Your real problem is that you don't understand that division a/b, when a and b are of type int, produces a result of type int.
I would also suggest not holding up Python as an exemplar of how C++ should handle such things. Python 2.x produced an integral-valued result on integral division too (albeit, with slightly different behaviour than in C++). Python 3.x introduced the so-called "true division". There was a lot of heated discussion in the Python community over that.
Another way to frame this question would be: what advantage does the
(type) expression offer over type (expression)?
Actually, they are almost the same...
(type) expression is a C-style cast
and
type (expression) also casts, but has limitations with respect to certain types(int*, const char* etc); Additionally, its also a constructor call for class types.