Floating point rounding woes
Is there a good way to chop off the value of a float beyond a certain accuracy? I want to get rid of anything smaller than 0.001 but keep the rest of the value. For example, 2.1005 would become 2.100.
(I'm doing this in C++, by the way.)
For a given precision p,
Find the magnitude of your number m=⌊log10 |x|⌋
Divide the number by 10m-p
Round off
Multiply by 10m-p
Would that do?
Find the magnitude of your number m=⌊log10 |x|⌋
Divide the number by 10m-p
Round off
Multiply by 10m-p
Would that do?
Yowza, that looks computationally expensive, but if there's no other way. Thanks for the reply!
Quote:Original post by griminventions
Yowza, that looks computationally expensive, but if there's no other way. Thanks for the reply!
There can very well be, that's just the first thing that came to my mind.
I came to the conclusion that instead of chopping out the tiny fractions giving me problems, I can ignore values below a threshold to solve the problem effectively. But thanks for the replies!
It's not very computation expensive. However, a float cannot represent a value like 2.1 exactly, so you will still only get an approximation of that value.
I managed to decrease the frequency of the problem, but rounding errors are still causing trouble. I'll try the formula Fruny gave.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement