mlAnswer = ( ( ( degreesPLato->text().toInt() * 1000000 ) * 3800 ) / answer );
is the code in quesition
mlAnswer out puts -8223, while my calculator puts out 228000
debug output
12 * 1000000 * 3800 / 200000 = -8223
all data types are ints Please tell me what I'm doing wrong.
12 * 1000000 * 3800 = 45.6 billion.
This is out of range for a 4 byte signed integer, which is what int usually is. Try using long long instead.
The default type of an integer literal is int, unless the number is too big to fit in an int. As long as you are doing math operations between ints, the results remain as ints. 12 is an int, 1000000 is an int, and 3800 is an int. When you multiply them together, the result is still an int, even though it no longer fits. Add the LL suffix to make the integer literal a long long. i.e. 12LL, 1000000LL, 3800LL, etc...
You can fix this by reordering your operations:
12 * 1000000 * 3800 / 200000
Will overflow an int, however:
12 * 1000000 / 200000 * 3800
will not.
Note that this will only give the same answer if the numerator is an integer multiple of the denominator. Using LL is a better solution on platforms that support it, but if you are constrained to a 4 byte int type, this will at least stop overflow in more situations.
Related
I can't print 100000 * 100000 when I use COUT in C++. The output was 1410065408 instead of 10000000000. How can I fix that?
Thanks!
By default, integer literals are of type int which causes the overflow you have.
Use 100000LL to mark the number as long long and have a long long result.
https://en.cppreference.com/w/cpp/language/integer_literal
The value is truncated since 10000000000 is larger than the default interger type int max value (std::numeric_limit<int>::max()) ,
hex(10000000000) = 0x2540be400
hex(1410065408) = 0x540be400
You can see that the first byte is truncated.
To fix it:
100000LL * 100000
or cast it
static_cast<int64_t>(100000) * 100000
Earlier I came up with something, which I solved, but it got me later
let's take a look at a similar example of what I was on:
int b = 35000000; //35million
int a = 30000000;
unsigned long n = ( 100 * a ) / b;
Output: 4294967260
I simply changed a to unsigned long and the correct 85% output would come up, because a is a signed 32bit integer. But this got me later. There is no value assignment to a during ( 100 * a ) there is just simply a calculation and the correct value which is 3billion should come up instead of an overflow. To understand if there wasn't really an assignment to a I removed a from the code and manually write the value instead instead:
int b = 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
The big surprise was that the output is also: 4294967260
And of course value of 3billion can be assigned to an unsigned long.
My first thought was that ( 100 * 30000000 ) was causing an overflow, but then I asked "an overflow on what? there is nothing to be overflowed".
Then I changed b to unsigned long, which even most suprisingly the output was correct 85%.
In the first example changing a to unsigned long
int b = 35000000;
unsigned long a = 30000000;
unsigned long n = ( 100 * a ) / b;
and leaving bas an int as it is works, but on the second example it doesn't, what is occuring?
This might be a little overwhelming to let me re-write all examples with the ones who work and the ones who dont.
Works (Output = 85):
int b = 35000000;
unsigned long a = 30000000;
unsigned long n = ( 100 * a ) / b;
Works (Output = 85):
unsigned long b= 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
Doesn't works (Overflow):
int b = 35000000;
int a = 30000000;
unsigned long n = ( 100 * a ) / b;
Doesn't works (Overflow):
int b = 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
Let me explain what is occuring here.
On:
int b= 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
The value is incorrect because overflow happens at ( 100 * 30000000 )
But on:
unsigned long b= 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
The value is correct, so what is happening?
In the first example b is a int, as said by Tony, an overflow happens because the register where the temporary value of ( 100 * 30000000 )will be assigned is able to hold 32bit signed integers, that happens because 100 is an int and 30000000 is also an int AND because b is also an int, the register in this case are smart, when ALL values on the right side are int it assumes the values also have to be an int but when a mighty unsigned long comes to the party, it knows that dividing an int by an unsigned long, / b is wrong, so it stores the value of ( 100 * 30000000 ) to an unsigned long.
In C++, there are programming elements called "literal constants".
For example (taken from here):
157 // integer constant
0xFE // integer constant
'c' // character constant
0.2 // floating constant
0.2E-01 // floating constant
"dog" // string literal
So, back to your example, 100 * 30000000 is multiplying two ints together. That is why there is overflow. Anytime you perform arithmetic operations on operands of the same type, you get a result of the same type. Also, in the snippet unsigned long a = 30000000;, you are taking an integer constant 30000000 and assigning that to the variable a of type unsigned long.
To get your desired output, add the ul suffix to the end: unsigned long n = ( 100ul * 30000000ul ) / b;.
Here is a site that has explanations for the suffixes.
why /b when b is unsigned long is still an interesting question
Because 100 * 30000000 is performed before you divide by b and the operands are both of type int.
The maximum number that can be represented in a 32-bit signed integer without overflow is 2147483647. 100*30000000 is larger than that.
The type of an arithmetic operation is completely independent of the type of the variable you're storing it into. It's based on the type of the operands. If both operands are of type int, the result will be of type int too, and that result will then be converted before it is stored in the variable.
Works (Output = 85):
unsigned long b= 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
Not here, using:
#include <iostream>
int main() {
unsigned long b= 35000000;
unsigned long n = ( 100 * 30000000 ) / b;
std::cout << n << std::endl;
return 0;
}
the output is 527049830640 (and the compiler warned about the overflow even with the default warning level).
The point is that, as Mark Ransom already wrote, the type of an arithmetic operation is determined by the type of its operands.
The type of the constant 100 is int, as is the type of the constant 30000000 (assuming 32-bit or larger ints, would be long int if int is 16 bits). So the multiplication is performed at type int, and with 32-bit ints it overflows. The overflow is undefined behaviour, but wrap-around is the most common manifestation of that undefined behaviour, resulting in the value -1294967296. Then the result of the multiplication is converted to the type of b (since that is an unsigned type and - in C terminology - its integer conversion rank is not smaller than that of int) for the division.
Conversion to an unsigned integer type means reduction modulo 2^WIDTH. If the width of unsigned long is 32, the result of that last conversion is 2^32 - 1294967296 = 3000000000, resulting in the quotient 85. But if - as on my system - the width of unsigned long is 64 bits, the result of that conversion is 2^64 - 1294967296 = 18446744072414584320.
Another common solution is to typecast one of the constants to the larger, result type prior to operating on it. I prefer this method, since not everyone remembers all the possible suffixes. Including myself.
In this case, I'd use:
unsigned long n = ( (unsigned long)100 * 30000000 ) / b;
The sad part is that this is one thing assembly language—yes, assembly language—gets right that C, C++, and many other languages do not: The result of multiplying an M-bit integer by an N-bit integer is a (M+N)-bit integer, not a (max(M, N))-bit integer.
EDIT: Mark makes an interesting point: the compiler does not "look ahead" to where the result is stored in order to infer a result type. Thus, C++ demands that the result of any sub-expression, by itself, be deterministic. In other words, the exact type of 100 * 30000000 can always be determined without looking at any other piece of code.
I have three calculation to get the curent cpu frequency: (cycles per second)
_initialCycles = rdtsc(); //rdtsc function calculates the cpu cycles since init.
first:
------
unsigned int initialMillisec = (_timeVal.tv_sec)*1000+(_timeVal.tv_usec)/1000;
unsigned int cps1 = ((_initialCycles / initialMillisec) * 1000);
second:
-------
double initialMillisec2 = (_timeVal.tv_sec)*1000+(_timeVal.tv_usec)/1000.0;
unsigned int cps2 = (unsigned int)(_initialCycles / initialMillisec2 * 1000.0);
third:
------
unsigned long long initialUsec3 =
((unsigned long long)(_timeVal.tv_sec))*1000000+_timeVal.tv_usec) ;
unsigned int cps3 = (unsigned int)((_initialCycles / initialUsec3)* 1000000.0);
the thing is, cps1 cps2 cps3 suppose to have the same value, more or less..
but they don't. I get:
cps1 = 2824048000
cps2 = 3824609671
cps3 = 8000000
anyone knows why?
Your problem with integer types is in roundings. When you divide by some big number you loose significant digits. So, you should change the operation order between the multiplication and the division. First you should multiply by 1000 (or 1000000 in the case of long long) and only then divide.
Some examples of loosing the accuracy with the integers:
321 / 20 * 20 = 320;
321 / 75 * 75 = 300;
321 / 112 * 112 = 224
There are many other threads and processes running at the same time and the OS scheduler might inter fear with this method of measuring the frequency.
Try using the "cpufreq" utility to accurately get the current clock speed.
Operator precedence and implicit conversions.
Of course you need to make sure the operators get evaluated in the order you desire. My best advice: add parens if you would have to think twice to know the order without parens.
Then: you need to convert the ints to floats early, or you'll end up with integer division and ditto rounding errors.
unsigned int initialMillisec = _timeVal.tv_sec*1000 + _timeVal.tv_usec/1000;
unsigned int cps1 = (1.0 * _initialCycles / initialMillisec) * 1000.0;
would be my suggestion
I know this is stupid but I'm a quiet a noob in a programming world here is my code.
This one works perfectly:
#include <stdio.h>
int main() {
float x = 3153600000 ;
printf("%f", x);
return 0;
}
But this one has a problem:
#include <stdio.h>
int main() {
float x = 60 * 60 * 24 * 365 * 100 ;
printf("%f", x);
return 0;
}
So 60 * 60 * 24 * 365 * 100 is 3153600000 right ??? if yes then why does it produced different results ??? I got the overflow in the second one it printed "-1141367296.000000" as a result. Could anyone tell me why ?
You're multiplying integers, then putting the result in a float. By that time, it has already overflowed.
Try float x = 60.0f * 60.0f * 24.0f * 365.0f * 100.0f;. You should get the result you want.
60 is an integer, as are 24, 365, and 100. Therefore, the entire expression 60 * 60 * 24 * 365 * 100 is carried out using integer arithmetic (the compiler evaluates the expression before it sees what type of variable you're assigning it into).
In a typical 32-bit architecture, a signed integer can only hold values up to 2,147,483,647. So the value would get truncated to 32 bits before it gets assigned into your float variable.
If you tell the compiler to use floating-point arithmetic, e.g. by tacking f onto the first value to make it float, then you'll get the expected result. (A float times an int is a float, so the float propagates to the entire expression.) E.g.:
float x = 60f * 60 * 24 * 365 * 100;
Doesn't your compiler spit this warning? Mine does:
warning: integer overflow in
expression
The overflow occurs before the all-integer expression is converted to a float before being stored in x. Add a .0f to all numbers in the expression to make them floats.
If you multiply two integers, the result will be an integer too.
60 * 60 * 24 * 365 * 100 is an integer.
Since integers can go up to 2^31-1 (2147483647) such values overflows and becomes -1141367296, which is only then converted to float.
Try multiplying float numbers, instead of integral ones.
I need some division algorithm which can handle big integers (128-bit).
I've already asked how to do it via bit shifting operators. However, my current implementation seems to ask for a better approach
Basically, I store numbers as two long long unsigned int's in the format
A * 2 ^ 64 + B with B < 2 ^ 64.
This number is divisible by 24 and I want to divide it by 24.
My current approach is to transform it like
A * 2 ^ 64 + B A B
-------------- = ---- * 2^64 + ----
24 24 24
A A mod 24 B B mod 24
= floor( ---- ) * 2^64 + ---------- * 2^64 + floor( ---- ) + ----------
24 24.0 24 24.0
However, this is buggy.
(Note that floor is A / 24 and that mod is A % 24. The normal divisions are stored in long double, the integers are stored in long long unsigned int.
Since 24 is equal to 11000 in binary, the second summand shouldn't change something in the range of the fourth summand since it is shifted 64 bits to the left.
So, if A * 2 ^ 64 + B is divisible by 24, and B is not, it shows easily that it bugs since it returns some non-integral number.
What is the error in my implementation?
The easiest way I can think of to do this is to treat the 128-bit numbers as four 32-bit numbers:
A_B_C_D = A*2^96 + B*2^64 + C*2^32 + D
And then do long division by 24:
E = A/24 (with remainder Q)
F = Q_B/24 (with remainder R)
G = R_C/24 (with remainder S)
H = S_D/24 (with remainder T)
Where X_Y means X*2^32 + Y.
Then the answer is E_F_G_H with remainder T. At any point you only need division of 64-bit numbers, so this should be doable with integer operations only.
Could this possibly be solved with inverse multiplication? The first thing to note is that 24 == 8 * 3 so the result of
a / 24 == (a >> 3) / 3
Let x = (a >> 3) then the result of the division is 8 * (x / 3). Now it remains to find the value of x / 3.
Modular arithmetic states that there exists a number n such that n * 3 == 1 (mod 2^128). This gives:
x / 3 = (x * n) / (n * 3) = x * n
It remains to find the constant n. There's an explanation on how to do this on wikipedia. You'll also have to implement functionality to multiply to 128 bit numbers.
Hope this helps.
/A.B.
You shouldn't be using long double for your "normal divisions" but integers there as well. long double doesn't have enough significant figures to get the answer right (and anyway the whole point is to do this with integer operations, correct?).
Since 24 is equal to 11000 in binary, the second summand shouldn't change something in the range of the fourth summand since it is shifted 64 bits to the left.
Your formula is written in real numbers. (A mod 24) / 24 can have an arbitrary number of decimals (1/24 is for instance 0.041666666...) and can therefore interfere with the fourth term in your decomposition, even once multiplied by 2^64.
The property that Y*2^64 does not interfere with the lower weight binary digits in an addition only works when Y is an integer.
Don't.
Go grab a library to do this stuff - you'll be incredibly thankful you chose to when debugging weird errors.
Snippets.org had a C/C++ BigInt library on it's site a while ago, Google also turned up the following: http://mattmccutchen.net/bigint/