Different results with Polyfit?

7 views (last 30 days)
Jules Ray on 3 Mar 2017
Edited: John D'Errico on 3 Mar 2017
I'm using polyfit to get a simple lineal regression of degree 1
howver the coefficients from the lineal equation varies slightly. Is not a big variation but each time I run polyfit the coeficients are slightly different than the run before.
Indeed if I run polyfit in a loop or using a bootstrap I obtained several similar values but slightly different.
I know the results is ok and is probably related with the uncertainty of polyfit estimation, but I dont understand the mathematics behind this slight variation.
Does anyone have an idea why this happens?
Cheers

John D'Errico on 3 Mar 2017
It does not happen. IF you pass in exactly the same data (in the same order) into polyfit, calling polyfit the same way each time, it will return exactly the same result, time after time after time.
If you change the data in any way, then of course you will get different results. In fact, even changing the order of the data points is sufficient.
x = randn(100,1);
y = randn(100,1);
P1 =polyfit(x,y,1);
s = randperm(100);
P2 = polyfit(x(s),y(s),1);
P1 == P2
ans =
1×2 logical array
0 0
P1 - P2
ans =
1.7347e-17 6.9389e-17
So all I did was permute the data. Change the order of ANY set of floating point additions, subtracts, multiplies, etc., and you can get a slightly different result.
0.3 - 0.2 - 0.1
ans =
-2.7756e-17
-0.1 - 0.2 + 0.3
ans =
-5.5511e-17
What I have described is NOT due to the accuracy of polyfit, but simply a basic feature of floating point arithmetic. If you are having a different problem, I cannot guess what it is, since you have told us virtually nothing about what you really did. People screw up all sorts of things in all sorts of different ways. So without knowing true specifics, all we can do is make guesses.
John D'Errico on 3 Mar 2017
I think you don't understand what a bootstrap does.
https://en.wikipedia.org/wiki/Bootstrapping_(statistics)
In there, the very first line says "In statistics, bootstrapping is any test or metric that relies on random sampling with replacement."
The help for bootstrp says the same thing.
"bootstrp creates each bootstrap sample by sampling with replacement from the rows of the non-scalar data arguments"
The variability is NOT due to polyfit. This is not a question of each time you use polyfit. Infact, you are not calling polyfit directly at all. The issue is which subset of your data that bootstrp passes to polyfit. When you do random sampling, you will get different results. Can you expect a fixed result given random sampling?