域错误问题

时间:2013-05-29 16:12:03

标签: vector

当我使用⌈⌿(⌈/ c) - ⌊⌿(⌊/ c)计算空矢量(v←⍳0)中最大和最小数字之间的差异时,它会给我一个域错误。此语句适用于常规向量和矩阵。

如何处理异常,以便在向量为空时不会出现错误?它不应该返回任何东西或只返回零。

2 个答案:

答案 0 :(得分:2)

守卫是最好的方法:

{0=⍴⍵:0 ⋄ (⌈/⍵)-⌊/⍵}

请注意,实际上并不真正需要使用两个减少,一个具有轴指定。也就是说,如果你想让它处理任何维度的简单数组的所有元素,只需先对参数进行处理:

     {0=⍴⍵:0 ⋄ (⌈/⍵)-⌊/⍵},10 10 ⍴⍳100
99

或者对于任何结构或深度的数组,您可以使用“super ravel”:

     {0=⍴⍵:0 ⋄ (⌈/⍵)-⌊/⍵}∊(1 2 3)(7 8 9 10)
9

请注意,quadML(迁移级别)必须设置为3,以确保epsilon是“超级ravel”。

还要注意在矩阵上操作时的等效性:

     ⌈⌿⌈/10 10 ⍴⍳100
99
     ⌈/⌈/10 10 ⍴⍳100
99
     ⌈/⌈⌿10 10 ⍴⍳100
99
     ⌈⌿⌈⌿10 10 ⍴⍳100
99   

在这种情况下不需要使用轴减少,并且模糊了意图并且也可能更昂贵。最好只是把整个事情搞得一团糟。

答案 1 :(得分:1)

正如我在评论中提到的Dyalog APL has guards,它可以用于条件执行,因此你可以简单地检查空向量并给出不同的答案。

然而,这可以用更传统的/纯粹的APL方法实现。

此版本仅适用于1维

以APL字体:

Z←DIFFERENCE V
⍝ Calculate difference between vectors, with empty set protection
⍝ Difference is calculated by a reduced ceiling subtracted from the reduced floor
⍝ eg. (⌈⌿(⌈V)) - (⌊⌿(⌊V))
⍝ Protection is implemented by comparison against the empty set ⍬≡V
⍝ Which yields 0 or 1, and using that result to select an answer from a tuple
⍝ If empty, then it drops the first element, yielding just a zero, otherwise both are retained
⍝ eg. <condition>↓(a b) => 0 = (a b), 1 = (b)
⍝ The final operation is first ↑, to remove the first element from the tuple.
Z←↑(⍬≡V)↓(((⌈⌿(⌈V)) - (⌊⌿(⌊V))) 0)

或者用括号表示,对于没有字体的人。

Z{leftarrow}DIFFERENCE V
{lamp} Calculate difference between vectors, with empty set protection
{lamp} Difference is calculated by a reduced ceiling subtracted from the reduced floor
{lamp} eg. ({upstile}{slashbar}({upstile}V)) - ({downstile}{slashbar}({downstile}V))
{lamp} Protection is implemented by comparison against the empty set {zilde}{equalunderbar}V
{lamp} Which yields 0 or 1, and using that result to select an answer from a tuple
{lamp} If empty, then it drops the first element, yielding just a zero, otherwise both are retained
{lamp} eg. <condition>{downarrow}(a b) => 0 = (a b), 1 = (b)
{lamp} The final operation is first {uparrow}, to remove the first element from the tuple.
Z{leftarrow}{uparrow}({zilde}{equalunderbar}V){downarrow}((({upstile}{slashbar}({upstile}V)) - ({downstile}{slashbar}({downstile}V))) 0)

和图像为了保存...

APL Difference Function

更新。多维

Z←DIFFERENCE V
⍝ Calculate difference between vectors, with empty set protection
⍝ Initially enlist the vector to get reduce to single dimension
⍝ eg. ∊V
⍝ Difference is calculated by a reduced ceiling subtracted from the reduced floor
⍝ eg. (⌈/V) - (⌊/V)
⍝ Protection is implemented by comparison against the empty set ⍬≡V
⍝ Which yields 0 or 1, and using that result to select an answer from a tuple
⍝ If empty, then it drops the first element, yielding just a zero, otherwise both are retained
⍝ eg. <condition>↓(a b) => 0 = (a b), 1 = (b)
⍝ The final operation is first ↑, to remove the first element from the tuple.
V←∊V
Z←↑(⍬≡V)↓(((⌈/V) - (⌊/V)) 0)

APL Difference multi-dimensional