C++ Fractional Numbers

how to work with fractional data ? floating point numbers.

3 floating types :

the main difference is the amount of memory they occupy, and the size of data that they can represent.

  • long double size can be either 12 or 16 bytes of memory.

Precision

Precision is nothing but the number of digits you can represent with that type starting with the number that is in front of the decimal point.

Declaring floating point data

Set the precision in cout

We first need to add <iomanip> header file.

Sets the decimal precision to be used to format floating-point values on output operations. setprecision function.

Output :

Understanding the program

Float data type has precision of 7. So, for number1, the data is going to jumble up after 7 digits. Whatever comes after 7 digits is garbage.

Double data type has precision of 15. So, for number2, the data is going to jumble up after 15 digits.

Long double will have same precision as double or more.

Narrowing problems

When you initialize floating point variable with higher precision floating data, it will simply chop off extra digits. Below, 192400023.0f – we are using suffix ‘f’ to indicate it as floating point data.

float only accepts up to 7 digits of precision. But here, we are using above that. Some compilers can simply chop off extra digits and stores wrong data into the variable. Here, information is lost.

Initialize float variable with double data

Braced initialization will throw a compiler error for narrowing conversion. Here, we are initializing higher precision data and double type data.

However, if you use functional based initialization, it will not throw any compiler error. Instead, it silently performs narrowing conversion and you will get wrong results.

Scientific notation

It indicates power of 10 multiplier.

iomanip — https://cplusplus.com/reference/ios/scientific/

Memory representation

We use IEEE_754 format.

Infinity and NaN

For floating point data, if we divide by zero, it will give +inf/-inf depending the on number.

Also if you divide 0/0, it will result in nan.