Mathematica 对#^2 & 的不解解读//@范围[n] [英] Mathematica's puzzling interpretation of #^2 & /@ Range[n]

查看:33
本文介绍了Mathematica 对#^2 & 的不解解读//@范围[n]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Mathematica 对以下内容的回答感到困惑:

I'm puzzled by Mathematica's responses to the following:

ClearAll[n]
#^2 & /@ Range[n]
#^2 & /@ Range[n] // StandardForm

似乎连 Mathematica (8.0) 都不相信它刚刚说的话:

It seems that even Mathematica (8.0) doesn't believe what it has just said:

#^2 & /@ Range[5]
Range[5^2]

对正在发生的事情有什么想法吗?

Any thoughts about what is happening?

这个问题的原始上下文如下.我已经写了

The original context for this question was the following. I had written

PrimeOmega[Range[n]] - PrimeNu[Range[n]]

并且由于 n 会非常大(2^50),我想我可以通过将其重写为:

and since n was going to be very large (2^50), I thought I might save time by rewriting it as:

 PrimeOmega[#] - PrimeNu[#] &/@Range[n]

回想起来,这可能不是一个好主意.(我本可以使用 Module 仅计算"一次范围.)

Thinking back, that probably wasn't such a good idea. (I could have used Module to 'compute' the Range only once.)

推荐答案

由于 n 未定义,Range[n] 对自身求值.因此,Map 就像在任何其他符号头上一样作用于它,将你的函数映射到它的元素上——这里它只是 n

Since n is undefined, Range[n] evaluated to itself. Therefore, Map acts on it as on any other symbolic head, mapping your function on its elements - here it is just n

In[11]:= #^2 & /@ someHead[n]
Out[11]= someHead[n^2]

编辑

解决您编辑中的问题 - 对于数字 nRange 评估为一个列表,您会得到预期的结果(即,Range[5]^2.这就是求值的顺序.要得到Range[5^2],你可以使用#^2&/@Unevaluated[范围[5]],在这种情况下,一切都会发生,就像上面的符号 n 一样).事实上,Range 会针对非数字输入发出错误消息.此外,它与问题无关,但像 #^2& 这样的函数是 Listable,您不必映射它们.

Addressing the question in your edit - for numeric n, Range evaluates to a list all right, and you get the expected result (which is, Range[5]^2. It is all about the order of evaluation. To get Range[5^2], you could have used #^2&/@Unevaluated[Range[5]], in which case everything happens just like for symbolic n above) . In fact, Range issues an error message on non-numeric input. Also, it is tangential to the question, but functions like #^2& are Listable, and you don't have to map them.

这篇关于Mathematica 对#^2 & 的不解解读//@范围[n]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆