Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing probability in C++

I'm trying to represent a simple set of 3 probabilities in C++. For example:

a = 0.1  
b = 0.2  
c = 0.7

(As far as I know probabilities must add up to 1)

My problem is that when I try to represent 0.7 in C++ as a float I end up with 0.69999999, which won't help when I am doing my calculations later. The same for 0.8, 0.80000001.

Is there a better way of representing numbers between 0.0 and 1.0 in C++?

Bear in mind that this relates to how the numbers are stored in memory so that when it comes to doing tests on the values they are correct, I'm not concerned with how they are display/printed out.

like image 502
Dave Avatar asked Aug 14 '26 08:08

Dave


1 Answers

This has nothing to do with C++ and everything to do with how floating point numbers are represented in memory. You should never use the equality operator to compare floating point values, see here for better methods: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm

like image 158
lyricat Avatar answered Aug 16 '26 20:08

lyricat