1

In this example I'm trying to create an Array of length 5 where each ellement contains the number of times .3 can be summed without exceeding 1. i.e. 3 times. So each element should contain the number 3. Here is my code:

Array[(
  workingCount = 0; 
  workingSum = 0; 
  done = false; 
  While[! done, 
   workingSum = workingSum + .3; 
   If[workingSum > 1, done = true; workingCount, workingCount++]
  ])
  , 5]

In the 3rd to last line there I have workingCount without a ; after it because it seems like in Mathematica omitting the ; causes the value a statement resolves to to be returned.

Instead I get this:

{Null[1], Null[2], Null[3], Null[4], Null[5]}

Why does this happen? How can I get my program to do what I want it to do? i.e. In the context of the function passed to Array to initialize it's elements, how to I use complicated multi-line functions?

Thanks in advance.

4

2 回答 2

2

两件事情:

首先,在 Mathematica 中能够做到这一点的一种方法是

Array[
 Catch[
   workingCount = 0;
   workingSum = 0;
   done = False;
   While[! done,
    workingSum = workingSum + .3;
    If[workingSum > 1,
     done = True; Throw@workingCount,
     workingCount++]]] &,
 5]

其次,也是最重要的:你永远不应该在 Mathematica 中这样做!真的。

请访问例如Mathematica 的 Stack Exchange 站点,并阅读那里的问题和答案,以掌握编程风格。

于 2012-10-09T05:13:13.263 回答
1

您的问题来自这样一个事实,即您正在尝试初始化数组,但在没有显式函数调用的情况下尝试这样做 - 这是您需要做的。

有关 Mathematica 中数组的文档,请参见此处: http ://reference.wolfram.com/mathematica/ref/Array.html

除此之外,还有一些小错误(True 和 False 必须大写),这就是你想要做的:

f[x_] :=
  (
   workingCount = 0;
   workingSum = 0;
   done = False;

   While[done != True, workingSum = workingSum + 0.3; 
    If[workingSum > 1, done = True, workingCount++]
    ];
   Return[workingCount];
   );

Array[f, 5] (* The array here is generating 5 values of the return value of f[x_] *)
于 2012-10-09T05:12:37.110 回答