Increase precision of output in float and double

by iarnab_kundu, Nov 29, 2013, 1:47 PM

I have found one of the most awesome things on the internet. Everybody should try this!

Most of the times we hit a dead end in our codes just because our lousy computers print the floats upto 5 d/6 digits. We are unable to solve a problem. But I just found the solution to that. I have found the perfect function required to increase the number of digits.

First try the code without setprecision.

Then with it.

Run the codes and see the contrast yourself. If you are too lazy to do that look at my code for printing the digits of pi.

The magic happens by the function std::setprecision(n) or setprecision(n), where n is an integer denoting the precision. Replace n=50 to print 50 digits of floating numbers.

The above function is under iomanip.
#include <iomanip> or #include<iomanip.h>


#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout<<setprecision(50)<<22.0/7;

return 0;
}
This post has been edited 4 times. Last edited by iarnab_kundu, Nov 29, 2013, 6:05 PM

Comment

4 Comments

The post below has been deleted. Click to close.
This post has been deleted. Click here to see post.
Is there a java analog of this?

by AkshajK, Nov 29, 2013, 2:16 PM

The post below has been deleted. Click to close.
This post has been deleted. Click here to see post.
Well I am a novice at coding, Java is like greek to me. But Googling I found some results.
http://stackoverflow.com/questions/5195837/format-float-to-n-decimal-places
http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java/12684082#12684082
Well have a look at them and please tell me if I could contribute anything.

by iarnab_kundu, Nov 29, 2013, 3:08 PM

The post below has been deleted. Click to close.
This post has been deleted. Click here to see post.
uh I'm not sure if you know this, but you can't really get more than 15~17 digits of precision from a double as stored in the computer, so printing any digits after around the 18th is simply useless...

by math_explorer, Nov 29, 2013, 3:23 PM

The post below has been deleted. Click to close.
This post has been deleted. Click here to see post.
No I was unaware of that fact. Thanks!
Btw do you mean after that 15/17 digits rest are just approximations?
Is there a way to surpass this?

by iarnab_kundu, Nov 29, 2013, 3:28 PM

This blog reflects my thoughts on the mathematics that I grapple with. Hopefully these rumblings could be organized as to be palatable to a mathematical audience.

avatar

iarnab_kundu
Tags
About Owner
  • Posts: 866
  • Joined: Jan 12, 2011
Blog Stats
  • Blog created: Mar 9, 2011
  • Total entries: 42
  • Total visits: 27150
  • Total comments: 24
Search Blog
a