Re: [xsl] Unexpected result in sum

Subject: Re: [xsl] Unexpected result in sum
From: Abel Braaksma <abel.online@xxxxxxxxx>
Date: Fri, 09 Nov 2007 21:14:14 +0100
I'm not 100% sure I really understand your question (do you expect the minus sign or don't you?) but I think any problem like this lies in the fact that when you use sum() on undeclared values, you sum them as xs:double, which is an unprecise floating point type, resulting in the sum being close to zero, but not exactly zero. I haven't tried your code yet, but if you declare your $nodes variable as xs:decimal+ I think you will get the expected result:

<xsl:variable name="nodes" select="b" as="xs:decimal+"/>

When doing numerics, I always force myself to use typed variables. You can use any simple type with a Basic processor, and xs:decimal is a simple type.

Come to think of it, when you force yourself to *always* use typed variables, you will win on three ends: your code will be more readable, the processor will have more hints to optimize for speed and, most importantly, coding problems (bugs) will be found way easier because the compiler has more to tell you on each error.

Hope this points you in the right direction,

Cheers,
-- Abel Braaksma

Angela Williams wrote:
Why does this not output 0.00? When formatted, I end up with -$0.00.

I've read what I can find on negative zero, but can't see how this node
set and operation could produce it.

Using Saxon 8.9 processor (internal to Oxygen.)

Input:
<?xml version="1.0" encoding="UTF-8"?>
<a>
    <b>1103.86</b>
    <b>1829.30</b>
    <b>-853.77</b>
    <b>-243.17</b>
    <b>-1.11</b>
    <b>-1296.66</b>
    <b>588.52</b>
    <b>849.25</b>
    <b>-1976.22</b>
</a>

Output:
<?xml version="1.0" encoding="UTF-8"?>
<a>
   <sum-b>-2.2737367544323206E-13</sum-b>
   <sum-nodes>-2.2737367544323206E-13</sum-nodes>
</a>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
version="2.0">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/a">
        <a>
            <sum-b>
                <xsl:value-of select="sum(b)"/>
            </sum-b>

<xsl:variable name="nodes" select="b"/>

            <sum-nodes>
                <xsl:value-of select="sum($nodes)"/>
            </sum-nodes>
        </a>
    </xsl:template>
</xsl:stylesheet>

Thanks!
Angela Williams Office: 512.344.1547 ~ Fax: 512.397.6656
Angela.Williams@xxxxxxxxxxxxxxxxxx

Current Thread