Re: A question about basic operation

From: Rick Grubin (grubin AT ucar.edu)
Date: Thu Sep 02 2004 - 16:02:33 MDT

  • Next message: Kevin Mueller: "NCL vim syntax"

    Hi Kim Joo-Wan,

    Regarding your question about exponentiation and negative numbers in NCL:

    Please have a look at the NCL documentation for operator precedence in
    numeric expressions at:
        http://ngwww.ucar.edu/ngdoc/ng/ug/ncl/nclimplmt/expressns.html

    > > I found a strange thing in basic operation in NCL
    > >
    > > ncl 11> print( -(0.5)^2 )
    > > (0) 0.25
    > >
    > > but generally it is -0.25

    The "answer" of -0.25 that you're expecting you explain as:

    > > but conventionally is should be -(0.5)*(0.5) = -0.25

    indicating you're expecting the exponentiation to occur first, and then
    a negation of that result.

    > > It seems that the ncl does (-0.5)*(-0.5) = 0.25

    What NCL does is negate the numeric value, and then raise it to the
    provided exponent, following the rules described in the documentation
    weblink above. The example

    > ncl > x = 0.5
    > ncl > x2 = -x^2 ===> 0.25 [ treated as -x to be squared]

    demonstrates this.

    The examples

    > ncl > print( -(0.5^2) ) ===> -0.25
    > ncl > X2 = -(x^2) ===> -0.25

    clearly set operator precedence using the () grouping, forcing the
    exponentiation to occur first. This is what you *want* but won't
    get, unless you explicitly code it that way, due to the rules of
    operator precedence.

    For NCL, operator '-' takes precedence over operator '^'

    -Rick.

    --
    Rick Grubin                     Visualization + Enabling Technologies
    Scientific Computing Division   National Center for Atmospheric Research   
    grubin@ucar.edu                 303.497.1832
    

    _______________________________________________ ncl-talk mailing list ncl-talk@ucar.edu http://mailman.ucar.edu/mailman/listinfo/ncl-talk



    This archive was generated by hypermail 2b29 : Thu Sep 09 2004 - 08:04:44 MDT