Sin(pi) or cos(pi/2) problem with Matlab

41 views (last 30 days)
Kamuran
Kamuran on 10 May 2015
Answered: Karan Gill on 30 Jul 2015
Hi,
I know that not getting ZERO for sin(pi) or cos(pi/2) in Matlab is an ongoing problem. My problem is inputting functions like
f=x^7+cos(x)^4/sin(pi*x) this is an only example input. It can be different but when sin(pi*x) is not equal to zero I will get a really large value but not inf and there is a difference between really large value and inf. Is there way to avoid or automatically filter this error.
the function can be also like f=x^7+cos(x)^4/sin(x) and when/if x=pi I need the function to be inf.
Anybody has a solution for this problem.
Thanks

Answers (2)

James Tursa
James Tursa on 10 May 2015
Edited: James Tursa on 10 May 2015
Pre-test the value of x. E.g., for scalar x:
if( floor(x) == x )
f = inf;
else
f = x^7 + cos(x)^4 / sin(pi*x);
end
xp = x / pi;
if( floor(xp) == xp )
f = inf;
else
f=x^7+cos(x)^4/sin(x)
end
But are you really OK with this behavior, but in cases where x (or xp) is one bit off from being an integer value, f is not inf? Or do you really want f to be inf for some range of small deviations from multiples of pi?
  1 Comment
Kamuran
Kamuran on 10 May 2015
I would like to within small deviations of multiples of pi. But my major problem I don't know what function user will input to the code. There might be no sin or cos in the function. So I can not prepare for a specific function. I believe the only way out of this is to identify the problem to the user.

Sign in to comment.


Karan Gill
Karan Gill on 30 Jul 2015
If you have the Symbolic Math Toolbox, you can use sym to represent pi symbolically and calculate f . Then, use double to convert the answer back into type double. Try:
>> x = 0;
f = double(x^7+cos(x)^4/sin(sym(pi)*x))
f =
Inf

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!