0

我设置了一个笔记本来对方程中使用的数组中的数字进行详尽的搜索,如果方程等于定义的变量,则它返回方程中变量的值。唯一的问题是,最后一个 For 循环中的 If 语句从未运行过 true/false/neither 函数。我能够让它做任何事情的唯一方法是使用通用的 Print[blah],然后它通过所有 For 循环进行绝对打印每次迭代。这是我到目前为止所拥有的-

AvTarget := -95
arr := {1, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2, 2.2, 2.4, 2.7, 3, 3.3, 
  3.6, 3.9, 4.3, 4.7, 5.1, 5.6, 6.2, 6.8, 7.5, 8.2, 9.1, 10}
trueArr := {}
falseArr := {}
For[i = 1, i <= Length[arr], i = i + 1,
 For[j = 1, j <= Length[arr], j = j + 1,
  For[k = 1, k <= Length[arr], k = k + 1,
   If[Abs[
      AvTarget - (arr[[i]] + arr[[k]] + (arr[[i]] + arr[[k]])/
         arr[[j]])] < 1000, Append[trueArr, {i, j, k}], 
    Append[falseArr, 1], Append[falseArr, 0]]
   ]
  ]
 ]
Length[trueArr]
Length[falseArr]

我还没有处理过数学中的循环,所以我不确定问题是什么。

编辑 -好的,所以这段代码现在可以按照我需要的方式工作-

AvTarget = -95;
tol = 0.1;
arr := {1, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2, 2.2, 2.4, 2.7, 3, 3.3, 
  3.6, 3.9, 4.3, 4.7, 5.1, 5.6, 6.2, 6.8, 7.5, 8.2, 9.1, 10}
trueArr = {};
falseArr = {};
For[i = 1, i <= Length[arr], i++,
 For[j = 1, j <= Length[arr], j++,
  For[k = 1, k <= Length[arr], k++,
   If[Abs[
      AvTarget - (-(arr[[i]] + arr[[k]] + (arr[[i]]*arr[[k]])/
           arr[[j]]))] <= tol, 
    trueArr = Append[trueArr, {arr[[i]], arr[[j]], arr[[k]]}], 
    Append[falseArr, 1], Append[falseArr, 0]]
   ]
  ]
 ]
Length[trueArr]

From there if Length > 0 I can just add an If to display the results. What would be the best way to have all the results within the tolerance printed in order of closest to AvTarget?

4

3 回答 3

1

You should assign the return value of Append to the respective variable.

于 2013-03-17T09:04:19.730 回答
1

Append[trueArr, {i,j,k}] gives trueArr with {i,j,k} appended and then discards the result. You want trueArr = Append[trueArr, {i, j, k}]. Also, ":=" is the SetDelayed operator. You should be using "=".

于 2013-03-17T09:07:09.977 回答
1

Loops are almost always the wrong way to go with Mathematica. I rewrote your original code to

avTarget = -95;
arr := {1, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2, 2.2, 2.4, 2.7, 3, 3.3, 
  3.6, 3.9, 4.3, 4.7, 5.1, 5.6, 6.2, 6.8, 7.5, 8.2, 9.1, 10};
triples = Tuples[arr, 3];
trueArr = Select[triples, Abs[avTarget - (#[[1]] + #[[3]] + (#[[1]] + #[[3]])/#[[2]]) < 
    1000] &];
falseArr = Complement[triples,trueArr];

I've been using Mathematica for about 20 years, I can't recall ever needing loops. Sure, sometimes it's easier to express an algorithm using loops than the functional alternatives that Mathematica provides but you should really kick away the crutches that they provide and walk the Mathematica way.

于 2013-03-17T09:32:47.070 回答