Same code but different results on Mac and PC
31 次查看(过去 30 天)
显示 更早的评论
I was trying to prove the methods of moments in statistics using Matlab, where the first central moment should be equal to the mean and the second central moment should be equal to the variance.
Here I assume the mean of the distribution to be 105 and the variance being 10.
The following is my code:
clearvars
mu=105;
sigma2=10;
sigma = sqrt(sigma2);
xmin=mu-10*sigma2;
xmax=mu+10*sigma2;
n_grids = 100000;
x=linspace(xmin,xmax,n_grids);
fx = pdf('norm',x,mu,sigma);
fx = fx./sum(fx);
mu_verify = sum(x.*fx);
sigma2_verify = sum(((x-mu).^2).*fx);
sigma_2 = sum((x.^2).*fx) - mu_verify^2;
sigma2_verify and sigma_2 both should be 10, which is what I got from my PC, using Matlab R2022b 64 bit pc version.
However, when I switch to my Macbook Air (M2), using Matlab R2022b 64 bit mac version,
sigma2_verify and sigma_2 both became 3.1623, which is the same as sigma.
What can I do fix my Matlab on Macbook?
0 个评论
回答(2 个)
Shaik
2023-5-16
Hi Scott
It seems like you are experiencing a difference in the results of your code when running it on different platforms (PC and Mac). The issue might be related to the precision of floating-point calculations, which can sometimes lead to slight variations in the computed values.
To address this, you can try increasing the precision of your calculations by using the vpa function, which performs variable-precision arithmetic.
Steven Lord
2023-5-16
When you step through your code in both the Windows and Mac versions of MATLAB using the debugging tools in MATLAB, on which line of the code do you first see a major difference in the results?
Can you confirm that you're using the same function on both versions? You can check which function is being used by calling the which function. For pdf and sum:
which -all pdf
which -all sum
I want to check that you haven't accidentally created your own pdf.m or sum.m functions that are being called instead of the functions in Statistics and Machine Learning Toolbox or MATLAB respectively.
1 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!