0

I have defined a really basic function in matlab. It takes no input and returns an array of 10 floating point numbers. The problem I have is that when I run the function to return the array I want I get incorrect values, however when I substitute in a value and simply print out the value from within the function I get the correct answer?! I've posted samples from the code below:

% 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)

The array I want to calculate for starts at -8 so the results should match. Does anyone have any idea why they wouldn't? Cheers Jack

JMzance
  • 1,704
  • 4
  • 30
  • 49
  • Can you show what the numbers are and also what you expect them to be? I have a feeling this is a floating point precision misunderstanding – Dan Oct 14 '13 at 10:41
  • Yep sure thing, I expect (and I have verified this using mathematica/maple/by hand) to get 0.0979 which is what I get from the run where I use -8 directly but when I run on the array I get 0.0181 – JMzance Oct 14 '13 at 10:44
  • Yeah but what are you using for `alpha`, `d` and `h`? Please provide everything so that the problem can be reproduced – Dan Oct 14 '13 at 11:16
  • 1
    Alpha = 45 * pi / 180; d = 0.25; h = 1.0; – JMzance Oct 14 '13 at 11:18
  • 1
    The array is use is: x=-8.0:2.0:8.0 – JMzance Oct 14 '13 at 11:20

1 Answers1

1

You have left off a . before your /

% //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
Dan
  • 45,079
  • 17
  • 88
  • 157