Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xml 如何在xquery中计算变量的幂?_Xml_Xslt_Xquery - Fatal编程技术网

Xml 如何在xquery中计算变量的幂?

Xml 如何在xquery中计算变量的幂?,xml,xslt,xquery,Xml,Xslt,Xquery,如果我需要计算一个值为2^($blocksize)的变量“totalIPaddress”,那么这个变量的xquery语句是什么 <IPaddress> <startIPaddress>192.168.1.1</startIPaddress> <blocksize>4</blocksize> </IPaddress> 192.168.1.1 4. 除了math:pow之外,最简单的方法就是硬编码: (1, 2, 4, 8,

如果我需要计算一个值为2^($blocksize)的变量“totalIPaddress”,那么这个变量的xquery语句是什么

<IPaddress>
<startIPaddress>192.168.1.1</startIPaddress>
<blocksize>4</blocksize>
</IPaddress>

192.168.1.1
4.

除了math:pow之外,最简单的方法就是硬编码:

(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 4294967296)[$blocksize + 1]

XPath 2也适用。

递归是您的朋友:

declare function f:two-to-the($n as xs:integer) as xs:integer {
  if ($n = 0) then 1 else 2 * f:two-to-the($n - 1)
};

这里有一种计算幂的特别有效的方法——对数时间复杂度(O(log(N)):

declare function local:pow($x as xs:double , $n as xs:integer ) as xs:double
{
  if($n eq 0)
   then 1
   else
    (let $h := $n idiv 2,
         $halfResult := local:pow($x, $h)
      return
            if($n mod 2 eq 0)
              then $halfResult * $halfResult
              else $x * $halfResult * $halfResult
        )

};

local:pow(2,10)
产生预期的正确结果

1024

您试过了吗?您使用的是什么版本的XQuery?(和:JLRishe说了什么。)