POV-Ray : Newsgroups : povray.general : Help creating a sgn() function : Re: Help creating a sgn() function Server Time
2 Aug 2024 00:14:39 EDT (-0400)
  Re: Help creating a sgn() function  
From: Mike Williams
Date: 3 Mar 2005 15:08:27
Message: <4h693PAx62JCFwe0@econym.demon.co.uk>
Wasn't it Jo Jaquinta who wrote:
>Hey Folks,
>   I'm trying to create a sgn() function, like in BASIC. Where sgn(x) = 
>-1 if x < 0, +1 if x > 0 and 0 if x = 0.
>
>First I tried with a function:
>
>#declare sgn = function(xx) { #if (xx<0) -1 #else #if (xx>0) 1 #else 0 
>#end #end }

You can't use #if inside a function. You need to use "select".

This works:

        #declare sgn=function(xx){select(xx,-1,0,1)}

>But this dies with a "expected 'numeric expression', undeclared 
>identifier 'xx' found instead". I take this to mean you can't use a if 
>inside a function.
>
>So I tried with a macro:
>
>#macro sgn(xx)
>   #if (xx < 0)
>     -1
>   #else
>     #if (xx > 0)
>       1
>     #else
>       0
>     #end
>   #end
>#end
>
>But this gives me a Parse Error: Expected ')', # found instead on the 
>"-1" line.

I don't know the details of why that doesn't work, but you can write it
quite neatly with the "?" operator.

This works:

        #macro sgn(xx) (xx>0?1:(xx<0?-1:0)) #end


-- 
Mike Williams
Gentleman of Leisure


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.