I would like to remove float leftovers while retaining its type.
(i.e 3.14159f should become 3.0f)
What I can do so far is casting the type twice.
float f = 3.14159f;
float r = static_cast<float>(static_cast<int>(f));
Is this the correct way to do it? or is there any simpler way?
Thank you in advance.
The operation of "removing leftovers" is called truncation. C++ provides std::trunc function to do it (include <cmath> header):
float r = std::trunc(f);
Is this the correct way to do it?
No.
or is there any simpler way?
One single cast should be sufficient:
float r = static_cast<int>(f);
Also as #Baum mit Augen said in their comment:
"This fails for values that don't fit in an int"
So using std::trunc() solves that problem with correct error handling.
That is a correct way to do that, but you can also use floor:
std::cout << std::floor(3.14f); // prints 3
Related
I have a variable in my code that is a complex float. I know that it only has a real part and I just want to type cast it to a float variable.
This should be super simple I feel but you can't just type cast and can't find the answer anywhere after over an hour of searching. Any help would be greatly appreciated!
There really isn't a "default" way to cast from a complex<float> to a float, because there are many interpretations:
Do you want the magnitude of the complex number? (sqrt(re*re + im*im))
Do you want the magnitude squared? This avoids the expensive square root.
Do you want the real portion only?
Some frameworks that do a lot with Digital Signal Processing (such as X-Midas, Midas 2K, PicklingTools) explicitly do not allow such conversions. They make the user pick the appropriate conversion so the user doesn't lose information in the transformation. Having said, if you want just the real component, I feel some of the answers above were fine. Here's a full, standalone program that illustrates:
#include <complex>
#include <iostream>
using namespace std;
int main()
{
complex<float> cf(1.1, 2.2);
float real_portion_only = cf.real();
cout << real_portion_only << endl;
}
The compile line and run looks like:
% g++ comp.cc -o comp
% ./comp
1.1
Is there any predefined type which can switch between float and double in some specific condition.
For example, some type, I would like this type be float; sometimes I need this type becomes double.
Use always double, it is recommended everywhere, if you don't have huge arrays in your program. This is a thing that I learned in programming competitions and because of which I failed many times previously because of precision problems.
It is not clear what you want to do. As #thecoder suggested the simplest option is to just use double. To convert it to float you just assign it:
double d = 0.1;
float f = d;
However, if you need to write code that must work both for float and double, use a template:
template<NumberT>
NumberT sum(NumberT first, NumberT second) {
return first + second;
}
As strange as it may seems, I can't find how to cleanly convert a float to an int.
This technique
int int_value = (int)(float_value + 0.5);
triggers a
warning: use of old-style cast
in gcc.
So, what is the modern-style, simple way to convert a float to an int ? (I accept the loss of precision of course)
As Josh pointed out in the comments, + 0.5 is not very reliable. For extra security you could combine a static_cast with std::round like so:
int int_value = static_cast<int>(std::round(float_value));
For the casting part, see this excellent post for an explanation.
try:
int int_value = static_cast<int>(float_value + 0.5);
FYI: different casts in C++ gave a very good explanation about those 4 casts introduced in C++.
You could also consider
int int_value = boost::lexical_cast<int>(float_value);
lexical_cast has the benefit of working for all primitive types, and stl strings etc. It also means you don't have to do the (float_value + 0.5) stuff.
double r2 = dx * dx + dy * dy;
double r3 = r2 * sqrt(r2);
Can the second line be replaced by something faster? Something that does not involve sqrt?
How about
double r3 = pow(r2,1.5);
If sqrt is implemented as a special case of pow, that will save you a multiplication. Not much in the grand scheme of things mind!
If you are really looking for greater efficiency, consider whether you really need r^3. If, for example, you are only testing it (or something derived from it) to see whether it exceeds a certain threshold, then test r2 instead e.g.
const double r3_threshold = 9;
//don't do this
if (r3 > r3_threshold)
....
//do do this
const double r2_threshold = pow(r3_threshold,2./3.);
if (r2 > r2_threshold)
....
That way pow will be called only once, maybe even at compile time.
EDIT If you do need to recompute the threshold each time, I think the answer concerning Q_rsqrt is worth a look and probably deserves to outrank this one
Use fast inverse sqrt (take the Q_rsqrt function).
You have:
float r2;
// ... r2 gets a value
float invsqrt = Q_rsqrt(r2);
float r3 = r2*r2*invsqrt; // x*x/sqrt(x) = x*sqrt(x)
NOTE: For double types there is a constant like 0x5f3759df which can help you write a function that handles also double data types.
LATER EDIT: Seems like the method has been already discussed here.
LATER EDIT2: The constant for double was in the wikipedia link:
Lomont pointed out that the "magic number" for 64 bit IEEE754 size
type double is 0x5fe6ec85e7de30da, but in fact it is close to
0x5fe6eb50c7aa19f9.
I think another way to look at your question would be "how to calculate (or approximate) sqrt(n)". From there your question would be trivial (n * sqrt(n)). Of course, you'd have to define how much error you could live with. Wikipedia gives you many options:
http://en.wikipedia.org/wiki/Methods_of_computing_square_roots
I was working on something else, but everything came out as zero, so I made this minimalistic example, and the output is still 0.
#include <iostream>
int main(int argc, char** argv)
{
double f=3/5;
std::cout << f;
return 0;
}
What am I missing?
You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number:
double f = 3.0 / 5;
It doesn't need to be .0, you can also do 3./5 or 3/5. or 3e+0 / 5 or 3 / 5e-0 or 0xCp-2 / 5 or... There only needs to be an indicator involved so that the compiler knows it's supposed to perform the division as floating point.
Another possibility: double f=double(3)/5. That's much more typing, but it leaves no doubt to what you are doing.
Or simply use double f=.6, that also does the trick...
try this:
double f = 3.0/5.0;
this should fix your problem
Try putting a .0 after one of the divisors. This will convert them into floating point literals.
You are using integers. You can many things to make your constants double like leftaroundabout states, however that is not good clean good. It is hard to read and confusing. If you want 3 and 5 make them 3.0 and 5.0. Everyone will know what you mean if they are forced to read your code. Much of what he/she states really requires you to know C/C++ and how floats are storage to make heads or tails.
In case, you save your generic variables with int and would like to obtain the ratio as double:
using namespace std;
int main()
{
int x = 7;
int y = 4;
double ratio;
ratio = static_cast<double>(x)/static_cast<double>(y);
cout << "ratio =\t"<<ratio<< endl;
}