the screen outputs 2 different numbers one is .0016 which is the number it reads in as a float and the second is 0.001599999959581
which is apparently the double conversion of 0.0016
The problem I am having is that the program I am currently writing needs an insane amount of accuracy thus every number needs to be in a double form.
The only way I know how to read in numbers from a text file is by reading them in as floats, so....
I am wondering is there either a way of reading in numbers as doubles, or converting floats to doubles more accurately.
You can probably get a bit more accuracy with a long double, but you should recognise that all electronic calculating devices will have rounding errors. You may want to think closer on what accuracy you require and what errors you can expect from the native machine types.
In a sense, yes, but it applies to all languages since it is a result of the binary system used internally. The problem is in the conversion from decimal to binary. The number .0016 is representable in decimal with a terminating fraction, but in binary it is a repeating fraction. Since there is only so many bits to represent a number, it cannot be represented exactly (in binary). Converting to double will not change the situation.
Working on this more the best way that I found around this problem (tested only on .0016) was to read the line in as a string then using the atof command convert the string to a double.
I like your code Hammurabi, but the reason I am using fscanf is because I am reading in a highly formatted text file that contains many delimiters. Will fin give me the same flexibility when reading in these files, such as looking for delimiters, reading in single or multiple lines, etc?
1. How many significant figures do you require? If you want high precision, you should know how high you need it. Your calculations are only as accurate as your source data.
2. It doesn't really matter how you read the entries, but scanf is a tricky beast and is often more trouble than it's worth.
You can read a line and parse that too in C++ using stream, but if you can read your data file, it may not be worth changing it at this point.
1) I am writing a code in MATLAB that verifies what the C++ code outputs. Some of the numbers are e-5 or e-6 in precision. So I only need a little precision, but the major problem is that I need the roundoff error in MATLAB and C++ to be the same, the easiest way for me to do this is get 15 digits of precision in C++.
2) I will look into stream commands for future use, but I do have a handle on fscanf, and other similar functions. I am not here to argue which functions are best, but I can say that I know which functions I am more comfortable with, but I am always looking for better tools to do my job.