Matlab gets basic arithmetic completely wrong!
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Petter Stefansson
le 11 Août 2018
Commenté : Petter Stefansson
le 11 Août 2018
I just had a Matlab experience that made me question everything.
I have two vectors: v1 and v2. Both are of length 10 000 and in double-precision. If I plot them, they look like this:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/193613/image.png)
Clearly, these two vectors are very different - one contains values as high as 30 while the other one contains mostly zeros and maxes out at around 6.8.
So far so good. But now when I plot the difference between the two vectors ( v1-v2) I get this:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/193615/image.png)
And if I calculate the maximum absolute difference between the two:
max(abs(v1-v2))
I get 4.4409e-15! What is going on here!?
Clearly the maximum absolute difference should be around 30, not in the order of e-15 something. So what am I facing here? Is it:
- My Matlab installation that is broken
- My system that is broken and can’t do arithmetic correctly
- My brain that is broken and the result are correct
This is the code I use to replicate the results, and I’m attaching a .mat file with the v1 and v2 vectors:
% Load v1 and v2
load('TwoStrangeVectors.mat')
% Plot vector 1
subplot(3,1,1)
plot(v1)
title('vector #1'), xlim([1 10000])
% Plot vector 2
subplot(3,1,2)
plot(v2)
title('vector #2'), xlim([1 10000])
% Plot vector 1 minus vector 2
subplot(3,1,3)
plot(v1 - v2)
title('vector #1 - vector #2'), xlim([1 10000])
I’m using Matlab 2018a on Windows 10 using a i7-8700K processor.
0 commentaires
Réponse acceptée
Dimitris Kalogiros
le 11 Août 2018
Modifié(e) : Dimitris Kalogiros
le 11 Août 2018
Vector v1 is corrupted. It contains "NaN" at the most of its values. Matlab subtracts only at positions where v1 contains valid numbers.
Run the following script, to see what I mean:
close all;
clear all
% Load v1 and v2
load('TwoStrangeVectors.mat')
%define an area of interest
t=2000:2030;
% Plot vector 1
subplot(3,1,1)
plot(t,v1(t),'-ro'); zoom on; grid on;
title('a piece of vector #1') % xlim([1 10000])
% Plot vector 2
subplot(3,1,2)
plot(t,v2(t),'-b*'); zoom on; grid on;
title('a piece of vector #2') %xlim([1 10000])
% Plot vector 1 minus vector 2
subplot(3,1,3)
plot(t, v1(t)-v2(t), '-ms'); zoom on; grid on;
title(' a piece of vector #1 - vector #2')
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!