ursmooth
ursmooth

Reputation: 311

Matlab reading numbers with higher precision

I have made this scripts that calculates the frequency of a given dataset, but matlab is not precise enough, is it possible to make matlab read in more accurat numbers and not cut off the numbers? I want it to use 8 digits (0.12345678) instead of 4 (0.1234) that is does now

fid = fopen('forceCoeffs.dat','rt');
A = textscan(fid, '%f%f%f%f%f%f', 'HeaderLines',9,'Collect', 9);
A = A{1};
fclose(fid);

t = A(:,1);

Fs = 1/(A(1,1));
x = A(:,2)

x = detrend(x,0);
xdft = fft(x);
freq = 0:Fs/length(x):Fs/2;
xdft = xdft(1:length(x)/2+1);
plot(freq,abs(xdft));
[~,I] = max(abs(xdft));
fprintf('Maximum occurs at %d Hz.\n',freq(I)); 

File: https://drive.google.com/file/d/0B9CEsYCSSZUSb1JmcHRkbFdWYUU/view?usp=sharing

Upvotes: 1

Views: 335

Answers (3)

nalyd88
nalyd88

Reputation: 5148

Thank you for including the forceCoeffs.dat file as it allowed me to run your code. Here is an explanation of what you are seeing.

First I want to point out that MATLAB is not rounding anything. You can check the data type of A to ensure you have enough precision.

>> class(A)

ans =

double

And since you are reading in the file using %f for each column, MATLAB will use all the bits provided by the double type. Ok, now take a look at the contents of your file. The first column has only 2 decimals of precision at most.

0.05            -7.013874e-09   1.410717e+02    -6.688450e-02   -3.344226e-02   -3.344224e-02
...
349.95          -1.189524e-03   1.381022e+00    -2.523909e-01   -1.273850e-01   -1.250059e-01
350             -1.423947e-03   1.380908e+00    -2.471767e-01   -1.250123e-01   -1.221644e-01

Since no more is needed MATLAB only prints four decimal places when you look at the variable in the variable explorer. Try looking at one of the other columns to see what I am talking about. I commented out the A = A{1} part of your code and looked at the second column. When clicking on the number you see the full precision.

enter image description here

Upvotes: 2

xiawi
xiawi

Reputation: 1822

To get more than 4 digits precision, you can use

format long

However, to get exactly 8 digits, you need to round it. If your number is a then let use:

format long
round(1e8*a)*1e-8

Upvotes: 0

user7024314
user7024314

Reputation:

You can use a long type to display 16 digits

Upvotes: 0

Related Questions