【问题标题】:problems with basic arithmetic in a function (Matlab)函数中的基本算术问题(Matlab)
【发布时间】:2013-10-21 21:41:12
【问题描述】:

我在 matlab 中定义了一个非常基本的函数。它不接受任何输入并返回一个由 10 个浮点数组成的数组。 我遇到的问题是,当我运行函数以返回我想要的数组时,我得到了不正确的值,但是当我替换一个值并简单地从函数中打印出该值时,我得到了正确的答案?! 我已经从下面的代码中发布了示例:

% Calculate the terms in our expression
FirstTerm  = sin(Alpha)*(atan(x+d)-atan(x-d));
SecondTerm = cos(Alpha)*0.5*log(((x+d).^2+h.^2)/((x-d).^2+h.^2));

% Combine and return result
Result = 2 * (FirstTerm - SecondTerm)

FirstTermTemp  = sin(Alpha)*(atan(-8+d)-atan(-8-d));
SecondTermTemp = cos(Alpha)*0.5*log(((-8+d).^2+h.^2)/((-8-d).^2+h.^2));
ResultTemp = 2 * (FirstTermTemp - SecondTermTemp)

我要计算的数组从 -8 开始,因此结果应该匹配。有谁知道他们为什么不这样做? 干杯 杰克

【问题讨论】:

  • 你能说明这些数字是什么以及你期望它们是什么吗?我感觉这是对浮点精度的误解
  • 是的,我希望(我已经使用mathematica/maple/手动验证了这一点)得到0.0979,这是我从直接使用-8的运行中得到的,但是当我继续运行时我得到的数组 0.0181
  • 是的,但是alphadh 使用的是什么?请提供一切,以便问题可以重现
  • Alpha = 45 * pi / 180; d = 0.25; h = 1.0;
  • 使用的数组是:x=-8.0:2.0:8.0

标签: matlab function arithmetic-expressions


【解决方案1】:

您在/ 之前留下了.

% //Calculate the terms in our expression
FirstTerm  = sin(Alpha)*(atan(x+d)-atan(x-d));
SecondTerm = cos(Alpha)*0.5*log(((x+d).^2+h.^2)./((x-d).^2+h.^2));
% //Combine and return result
Result = 2 * (FirstTerm - SecondTerm)

Result =

 Columns 1 through 7:

   0.097944   0.133866   0.208270   0.425797   0.692904  -0.140347  -0.124798

 Columns 8 and 9:

  -0.095581  -0.076166

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多