如何强制 J 给出错误而不是错误地返回无穷大?

How to force J to give error instead of incorrectly returning infinity?

如果您指示 J 在默认精度名词上计算一个大的结果,您很快就会 运行 进入结果为无穷大的情况 _。这很不和谐,因为无穷大在数学上意味着什么。

当超过标准精度时,如何指示 J 给出错误而不是无穷大?我可以在我的 J 安装中将其设置为默认值吗?

例如

   !1000x  NB. Extended precision gives large finite result.
4023872600770937735437024339230039857193748642107146325437999104299385123986290205920442084869694048004799886101971960586316668729948085589013238296699445909974245040870737599188236277271887325197795059509952761208749754624970436014182780946464962910563938...

   !1000  NB. Default precision claims infinity. I'd generally prefer an error.
_

这可能不完全符合您的要求,因为它使用格式外连词 8!:0 将无穷大更改为您想要的任何值(包括 'error')。当然,它只是看起来像一个错误;它真正做的是用 'error' 替换 '_' 所以它可能不是你想要的。结果也是盒装字符串,可能不符合您的限制条件。

   inf=: 'd<error>'&(8!:0)
   % i.6
_ 1 0.5 0.333333 0.25 0.2
   inf % i.6
┌─────┬───────────┬───────────┬───────────┬───────────┬───────────┐
│error│1.000000000│0.500000000│0.333333333│0.250000000│0.200000000│
└─────┴───────────┴───────────┴───────────┴───────────┴───────────┘

更多信息可以在 8!: J 词典中的外国连词词条中找到。 http://www.jsoftware.com/help/dictionary/dx008.htm

由于您的评论表明您确实想要触发错误,因此您可以使用断言。用于在显示之前测试“_”结果的关键字,但它是基于动词的,并且没有我所知道的全局设置。

   9!:35 [ 1 NB. to set the assert. flag on
   test =: 3 : 0
​assert. _~:%y  NB. to see if _ shows up in the result of %y
​%y
​)
   test 1 + i.5
1 0.5 0.333333 0.25 0.2
   test  i.5
|assertion failure: test
|   _~:%y

完成您想要做的事情的最直接方法是使用 assert. 重新定义您希望从中获得此行为的每个原语。这可能会对性能产生影响。

   SafeFactorial =: 3 : 0
p =. ! y
assert. p < _
assert. p > __
p
)
   SafeFactorial 5
120
   SafeFactorial 50
3.04141e64
   SafeFactorial 500
|assertion failure: SafeFactorial
|   p<_

来自评论的重要警告:

J is an array oriented language, and it's a rare circumstance where one is operating only on a single number. Typically the input to functions like factorial are arrays of multiple numbers, and so if you design a function to throw an error like this, it will preclude you from getting any results at all, even correct results if one atom is bad.

换句话说,在对数组进行操作时,无限结果通常是一种理想的行为。在引入额外的故障点之前,您应该仔细考虑。

我的目标是获得数学上正确的结果。我突然得出结论,我应该尽早失败,而不是像在 Java 中那样给出不正确的结果。 Dane 和 Eelvex 完全满足了我的要求,他们应得的。

一些观察可能会帮助其他人进入 J 思维模式:

首先,我已经知道扩展精度字面量,并且知道将整数转换为扩展精度的动词 x:。如果默认情况下我想要数学上正确的结果,我应该养成使用这些东西的习惯。

其次,我已经观察过像 e.g. 这样的动词。 dyadic i. which return 过大的结果而不是失败。这在 J 中很常见,我应该学会过滤我不想要的结果,而不是让我的程序一直出错。