Re: Strange results for simple calculations

*To*: mathgroup at smc.vnet.net*Subject*: [mg109533] Re: Strange results for simple calculations*From*: Tomas Garza <tgarza10 at msn.com>*Date*: Tue, 4 May 2010 06:28:47 -0400 (EDT)

Hi, I suggest you use a more Mathematica-like approach (I didn't bother to look at your code , which seems to go back to the Fortran era). For example: In[1]:== f==Fit[data,{1,x,x^2,x^3,x^4},x] Out[1]== 71.1857-5.08926 x+0.135228 x^2-0.00158225 x^3+6.88183*10^-6 x^4 In[2]:== f/.x->Transpose[data][[1]] Out[2]== {0.014078,0.0144066,0.0190227,0.0265257,0.0356803,0.0454164,0.0548289,0.0631781,0.0698893,0.074553,0.0769248,0.0769256,0.0746413,0.0703231,0.0643874,0.0574156,0.0501543,0.0435154,0.0385759,0.0365778,0.0389285} In[3]:== (f/.x->Transpose[data][[1]])-Transpose[data][[2]] Out[3]== {-0.000761973,-0.00162336,0.00182768,0.00252567,0.00227129,-0.00128362,-0.00265106,-0.000706856,-0.00204567,-0.000247004,0.000534801,0.000535574,-0.000158696,0.000688145,0.00348742,0.0016356,-0.00151566,-0.00148455,-0.0020241,-0.00152217,0.00251855} In[4]:== Mean[%] Out[4]== -2.16197*10^-13 This is one order of magnitude greater than your result. -Tomas > Date: Mon, 3 May 2010 06:10:03 -0400 > From: astronerma at gmail.com > Subject: [mg109511] Strange results for simple calculations > To: mathgroup at smc.vnet.net > > Hi All, > I have a data which I fit with the polynomial of 4th order and then I > want to find the mean of the differences between the data and the > model: > > (* my data, 21 points *) > data == {{47.5, 0.01484}, {48.5, 0.01603}, {49.5, 0.017195}, {50.5, > 0.0240}, {51.5, 0.033409}, {52.5, 0.0467}, {53.5, 0.05748}, > {54.5,0.063885}, {55.5, 0.071935}, {56.5, 0.0748}, {57.5, 0.07639}, > {58.5, 0.07639}, {59.5, 0.0748}, {60.5, 0.069635}, {61.5, 0.0609}, > {62.5, 0.05578}, {63.5, 0.05167}, {64.5, 0.0450}, {65.5, 0.0406}, > {66.5, 0.0381}, {67.5, 0.03641}}; > > (* polynomial fit *) > f == Fit[data, {1, x, x^2, x^3, x^4}, x] > > (* differences between the data an model *) > var == Table[data[[i, 2]] - f /. x -> data[[i, 1]], {i, 1, > Length[data]}] > > (* calculate mean *) > Mean[var] > > My result is: -3.65422*10^-14 which I find "a bit" underestimated. > Same goes wrong if I just want to do Sum[var]. > Now compare the two loops where the difference is only in the upper > limit of the sum 20 or 21: > > (* loop 1 *) > i == 1; > a == 0; > While[i <== 21, > a == a + var[[i]]; > i == i + 1; > ] > a > > (* loop 2 *) > i == 1; > a == 0; > While[i <== 20, > a == a + var[[i]]; > i == i + 1; > ] > a > > First loop returns -7.67386*10^-13 the second 0.00251855. So, is there > something wrong with the last point in my table var? How about I > change the initial value of i and let it count till 21, > > (* loop 3 *) > i == 2; > a == 0; > While[i <== 21, > a == a + var[[i]]; > i == i + 1; > ] > a > > And the result is: -0.000761973! I am completely lost here. Could > someone please explain me what I am doing wrong? > > Cheers > Anna > >