Double multiplication giving rounded results - c++

double a = 2451550;
double b = .407864;
double c= a*b;
cout<<c;
I was expecting the results to be "999898.9892" but getting "999899". I need the actual unrounded result.Please suggest.

By default, iostreams output 6 digits of precision. If you want more, you have to ask for it:
std::cout.precision(15);

It can also be done using Manipulator setprecision like below.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a = 2451550;
double b = .407864;
double c= a*b;
cout<<setprecision(15)<<c;
}
Also, Usage of manipulator will make the code compact.

By default the precision of an std::iostream will show how many digits total to display and by default precision is 6. So, since your number has six digits before the decimal place it will not display any after the decimal.
You can change this behavior with the 'fixed' manipulator. 'precision' then changes to mean the number of digits to display after the decimal which is probably what you were expecting.
To always get four digits after the decimal you can do this:
cout << setprecision(4) << fixed << c;
However, keep in mind that this will always display four digits after the decimal even if they are zeros. There is no simple way to get 'precision' to mean at most x number of digits after the decimal place with std::iostreams.

Related

How can I specify how many numbers are there after decimal point?

Is there any way to determine how many numbers are there in my double after decimal point. for example double a=3.14259
If I make a new int b now, how can I make value of bequal to numbers after decimal point from a?
The short answer is, you can't.
first of all, a type like double has always the same number of binary digits after a (binary) period. That is called mantissa. in case of double that are 53 bits, meaning 52 bit after binary period, in decimal that are about 15 digits. For details you may have a look a IEEE_754 (double precision)
When you convert a double to a decimal string, you will in general never match exact decimal. For example the value 0.1 could not exactly represented by a double value. a printf may show "0.1" after applying rounding.
However, when you are dealing with some double calculations you will experience small deriviation like 0.10000000000012 or 0.09999999999987. What will you do in such cases?
And there is a mathematican problem which has nothing to do with c++ doubles:
_
0.1 is equal to 0.09
so your answer would either 1 or infinity
Here is one way to do it: Convert the decimal to a string, and find the size of the substring after the decimal point, as follows:
#include <iostream>
#include <string>
int main()
{
double a = 3.14259;
std::string a_string = std::to_string(a);
a_string.erase ( a_string.find_last_not_of('0') + 1, std::string::npos ); //Get rid
//of extra zeroes
std::cout << a_string.substr(a_string.find('.') + 1).size() << "\n";
//Print the size of the substring of the original string from the decimal point (here 5)
}
You could treat the fractional part as a string literal. Utilize the std::stringstream and std::string:
#include <iostream>
#include <string>
#include <sstream>
int main(){
double whole = 3.14259;
auto fractionalno = whole - static_cast<long>(whole); // or use std::modf()
std::stringstream ss;
ss << fractionalno;
std::string s = ss.str();
s.erase(0,2);
std::cout << "The number of digits is: " << s.size();
}
Floating point number does not provide the number of digits after the point. (It is not even the 'exact' value. It is an approximate value.)
But if you just want to make another integer to have the same number of digits after the point just on the screen, why don't you just count?
Here is Python code:
a = 4.0 / 7
# a is 0.5714285714285714
b = str(a)
# b (str(a)) is 0.571428571429, different with a.
nod = len(b[b.index('.'):])
_c = 9.0 / 7
c = float(int(_c * 10 ** nod)) / 10 ** nod

c++ long double printing all digits with precision

Regarding my question I have seen a post on here but did not understand since i am new to C++. I wrote a small script which gets a number from user and script prints out the factorial of entered number.
Once I entered bigger numbers like 30, script does not print out all the digits.Output is like 2.652528598 E+32 however What I want is exact number 265252859812191058636308480000000. Could someone explain how to get all digits in long double.Thanks in advance
You can set the precision of the output stream to whatever you want in order to get your desired results.
http://www.cplusplus.com/reference/ios/ios_base/precision/
Here is an extract from the page, along with a code example.
Get/Set floating-point decimal precision
The floating-point precision determines the maximum number of digits to be written on insertion operations to express floating-point values. How this is interpreted depends on whether the floatfield format flag is set to a specific notation (either fixed or scientific) or it is unset (using the default notation, which is not necessarily equivalent to either fixed nor scientific).
Using the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point. Notice that it is not a minimum, and therefore it does not pad the displayed number with trailing zeros if the number can be displayed with less digits than the precision.
In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The digits before the decimal point are not relevant for the precision in this case.
This decimal precision can also be modified using the parameterized manipulator setprecision.
// modify precision
#include <iostream> // std::cout, std::ios
int main () {
double f = 3.14159;
std::cout.unsetf ( std::ios::floatfield ); // floatfield not set
std::cout.precision(5);
std::cout << f << '\n';
std::cout.precision(10);
std::cout << f << '\n';
std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed
std::cout << f << '\n';
return 0;
}
Possible output:
3.1416
3.14159
3.1415900000
Notice how the first number written is just 5 digits long, while the second is 6, but not more, even though the stream's precision is now 10. That is because precision with the default floatfield only specifies the maximum number of digits to be displayed, but not the minimum.
The third number printed displays 10 digits after the decimal point because the floatfield format flag is in this case set to fixed.

Convert a double to fixed decimal point in C++

I have a double variable in C++ and want to print it out to the screen as a fixed decimal point number.
Basically I want to know how to write a function that takes a double and a number of decimal places and prints out the number to that number of decimal places, zero padding if necessary.
For example:
convert(1.235, 2)
would print out
1.24
and
convert(1, 3)
would print out
1.000
so the function works as
convert(number as double, number of decimal places)
and simply prints out the required value to standard output (cout).
Does anyone know how to do this?
Thanks in advance.
Assuming I'm remembering my format strings correctly,
printf("%.*f", (int)precision, (double)number);
Look at the setprecision manipulator which should give you the idea
There is no such thing as a "fixed decimal place" number. The convert function will need to be the function that actually prints it out. I would suggest getting the whole part of the number, then print it. If [decimal places]>0 then print a decimal place, then print each decimal individually like: floor((n*log(10,d))%10); <-- just an idea, not actual code.
#include <iomanip>
#include <iostream.h>
// print a float, x places of precision
void convert (double number, int x)
{
cout << setprecision(x) << number << endl;
}
int main()
{
double a = 1.234;
convert (a,2);
}
output: 1.23
reference

Maximum Width of a Printed Double in C++

I was wondering, how long in number of characters would the longest a double printed using fprintf be? My guess is wrong.
Thanks in advance.
Twelve would be a bit of an underestimate. On my machine, the following results in a 317 character long string:
#include <limits>
#include <cstdio>
#include <cstring>
int main()
{
double d = -std::numeric_limits<double>::max();
char str[2048] = "";
std::sprintf(str, "%f", d);
std::size_t length = std::strlen(str);
}
Using %e results in a 14 character long string.
Who knows. The Standard doesn't say how many digits of precision a double provides other than saying it (3.9.1.8) "provides at least as much precision as float," so you don't really know how many characters you'll need to sprintf an arbitrary value. Even if you did know how many digits your implementation provided, there's still the question of exponential formatting, etc.
But there's a MUCH bigger question here. Why the heck would you care? I'm guessing it's because you're trying to write something like this:
double d = ...;
int MAGIC_NUMBER = ...;
char buffer[MAGIC_NUMBER];
sprintf(buffer, "%f", d);
This is a bad way to do this, precisely because you don't know how big MAGIC_NUMBER should be. You can pick something that should be big enough, like 14 or 128k, but then the number you picked is arbitrary, not based on anything but a guess that it will be big enough. Numbers like MAGIC_NUMBER are, not suprisingly, called Magic Numbers. Stay away from them. They will make you cry one day.
Instead, there's a lot of ways to do this string formatting without having to care about buffer sizes, digits of precision, etc, that let you just get on with the buisness of programming. Streams is one:
#include <sstream>
double d = ...;
stringstream ss;
ss << d;
string s = ss.str();
cout << s;
...Boost.Format is another:
#include <boost\format\format.hpp>
double d = ... ;
string s = (boost::format("%1%") % d).str();
cout << s;
Its defined in limits:
std::cout << std::numeric_limits<double>::digits << "\n";
std::cout << std::numeric_limits<double>::digits10 << "\n";
Definition:
digits: number of digits (in radix base) in the mantissa
Equivalent to FLT_MANT_DIG, DBL_MANT_DIG or LDBL_MANT_DIG.
digits10: Number of digits (in decimal base) that can be represented without change.
Equivalent to FLT_DIG, DBL_DIG or LDBL_DIG for floating types.
See: http://www.cplusplus.com/reference/std/limits/numeric_limits/
Of course when you print stuff to a stream you can use the stream manipulators to limit the size of the output.
you can decide it by yourself..
double a=1.1111111111111111111111111111111111111111111111111;
printf("%1.15lf\n", a);
return 0;
./a.out
1.111111111111111
you can print more than 12 characters..
If your machine uses IEEE754 doubles (which is fairly widespread now), then the binary precision is 53 bits; The decimal equivalent is approximately 15.95 (calculated via logarithmic conversion), so you can usually rely on 15 decimal digits of precision.
Consult Double precision floating-point format for a brief discussion.
For a much more in-depth study, the canonical paper is What Every Computer Scientist Should Know About Floating-Point Arithmetic. It gets cited here whenever binary floating point discussions pop up, and is worth a weekend of careful reading.

What is the meaning of numeric_limits<double>::digits10

What is the precise meaning of numeric_limits::digits10?
Some other related questions in stackoverflow made me think it is the maximum precision of a double, but
The following prototype starts working (sucess is true) when precision is greater that 17 ( == 2+numeric_limits::digits10)
With STLPort, readDouble==infinity at the end; with microsoft's STL, readDouble == 0.0.
Has this prototype any kind of meaning :) ?
Here is the prototype:
#include <float.h>
#include <limits>
#include <math.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
int main(int argc, const char* argv[]) {
std::ostringstream os;
//int digit10=std::numeric_limits<double>::digits10; // ==15
//int digit=std::numeric_limits<double>::digits; // ==53
os << std::setprecision(17);
os << DBL_MAX;
std::cout << os.str();
std::stringbuf sb(os.str());
std::istream is(&sb);
double readDouble=0.0;
is >> readDouble;
bool success = fabs(DBL_MAX-readDouble)<0.1;
}
numeric_limits::digits10 is the number of decimal digits that can be held without loss.
For example numeric_limits<unsigned char>::digits10 is 2. This means that an unsigned char can hold 0..99 without loss. If it were 3 it could hold 0..999, but as we all know it can only hold 0..255.
This manual page has an example for floating point numbers, which (when shortened) shows that
cout << numeric_limits<float>::digits10 <<endl;
float f = (float)99999999; // 8 digits
cout.precision ( 10 );
cout << "The float is; " << f << endl;
prints
6
The float is; 100000000
numeric_limits::digits10 specifies the number of decimal digits to the left of the decimal point you can represent without a loss of precision. Each type will have a different number of representable decimal values.
See this very readable paper:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2005.pdf
Although DBL_MAX ( = std::numeric_limits::digits10 = 15 digits) is the minimum guaranteed number of digits for a double, the DBL_MAXDIG10 value (= 17 digits) proposed in the paper has the useful properties:
Of being the minimum number of digits needed to survive a round-trip to string form and back and get the same double in the end.
Of being the minimum number of digits needed to convert the double
to string form and show different strings every time you get (A != B) in code.
With 16 or fewer digits, you can get doubles that are not equal in code,
but when they are converted to string form they are the same
(which will give the case where they are different when compared in the code,
but a log file will show them as identical - very confusing and hard to debug!)
When you compare values (e.g. by reviewing them manually by diff'ing two log files) we should remember that digits 1-15 are ALWAYS valid, but differences in the 16th and 17th digits MAY be junk.
The '53' is the bit width of the significand that your type (double) holds. The '15' is the number of decimal digits that can be represented safely with that kind of precision.
digits10 is for conversion: string → double → string
max_digits10 is for conversion: double → string → double
In your program, you are using the conversion (double → string → double). You should use max_digits10 instead of digits10.
For more details about digits10 and max_digits10, you can read:
difference explained by stackoverflow
digits10
max_digits10