Among all the floating point data type in C++ double is considered the best type for implementing a real number in our program.Here are some of the reasons why it is considered the best and preferred over the other.
In our program the floating point literal value i.e. number with fractional value,is of double type by default.
cout<< 34.5657 << endl ; //34.5657 is double type cout<< typeid(34.5657).name() ; //include the library <typeinfo> to use typeid operator
Since the fractional value is of double type using a fractional value with any type other then double can result in an unexpected output.Consider the program below.
float a=1 , b=6 , c , result ; c=a/b ; result=(c – (1/6) ) ; cout << result ;
The output is,
The output should be 0 but it isn’t why?.The actual reason is due to the difference in the precision of double and float type.
The value obtain from the evaluation of (1/6) is of double type but ‘c’ is a float type,this type difference gave rise to the unexpected output.If all the variables ‘a’,’b’,’c’ and ‘result’ were of double type the output would be 0.
Casting the value 1 and 6 to float type would also give the ‘result’ value as 0.But it is more secure to use double whenever we require fractional value because evaluation using floating point literal directly(like 1/6) is bound to happen in our program.
The second reason is size,float size is rather small so it might not be able to securely represent all the needed number for mathematical evaluation.What about long double? yes,long double can represent all the required number but it’s size is too large and so it might use up more resources than necessary.The perfect choice is double type,it can hold the necessary value(large or small) and it’s size is smaller than long double,so there is no fear of using up unnecessary resources.
The third reason is optimization.Some machines and compiler provide optimization for calculation using double type.It is always better to take advantage of this optimization if you want to built a faster and more efficient programs.