Unexpected MATLAB Answer Explained: Solving Complex Valued Equations | Homework

  • Thread starter Thread starter sara_87
  • Start date Start date
  • Tags Tags
    Matlab
AI Thread Summary
The MATLAB code provided results in a complex value due to floating-point precision errors, which cause the calculation of d to slightly exceed 0.1. This leads to an invalid input for the arcsine function, resulting in a complex output. To resolve this, users can employ the real function to extract the real part of the result or implement a check to ensure inputs remain within the valid range for the arcsine function. The discussion highlights the importance of understanding floating-point arithmetic in programming. Using y=real(asin(...)) is a straightforward solution to avoid complex results when expecting real outputs.
sara_87
Messages
748
Reaction score
0

Homework Statement



I put the following code into MATLAB:

d=(0.2+0.1)-0.2

y=(asin((d)/(0.1)))

The answer gives:

d=0.100000000000000

and i know that d/0.1 is equal to 1. so, i expect the answer of y to be
y=1.570796326794897 (which is pi/2)
but, MATLAB gives:

y= 1.570796326794897 - 0.000000021073424i

Homework Equations





The Attempt at a Solution



if i put:
d=0.1
then it would give:
y= 1.570796326794897

But, i want to know why the answer is complex valued when it uses 0.1000000000000000 ?

Thank you in advance.
 
Physics news on Phys.org
sara_87 said:
But, i want to know why the answer is complex valued when it uses 0.1000000000000000 ?

Thank you in advance.

The only reason I can think of is rounding error. The computer thinks .1000000000000 > .1, so when computing d/.1, you obtain a value greater than 1. Taking the arcsin of a value greater than 1, as you know, does not exist for real numbers. This is why there's a small complex term which contributes to the answer.
 
Hi Sara87. Floating point numbers on a computer generally can't be represented exactly, but this is usually hidden from the user by limiting the number of significant digits to which results are displayed. What's unusual in this case is that you are operating precisely on the boundary of the real domain (and the extended complex domain) of the asin() function.

BTW. Are you familiar with complex numbers?

Code:
> format long

> d=0.3
d =  0.300000000000000
> ((d - 0.2)/0.1)*1e16
ans = 9999999999999998

> d = 0.2+0.1
d = 0.300000000000000
> ((d - 0.2)/0.1)*1e16
ans = 10000000000000002
 
Last edited:
Thank you both.
Yes, i am familiar with the complex numbers.
So, how can i change my code so that is gives pi/2 instead of pi/2+ some complex number ?
 
There are several possible ways.

The simplest, if you're certain your result should be real, is: y = real(asin(...))

OR you could test if the argument is in [-1-delta ... +1+delta], then throw an error if it isn't and clip it back to [-1...1] if it is.
 
Thank you. I will use y=real(asin(...))
 
Back
Top