在mathematica中为线性方程创建随机系数
有没有办法为以下方程的 p1、p2、p3 和 p4 分配随机值?
p1 y1 + p2 y2 + p3 y3 = p4
假设 y1、y2 和 y3 是要求解的变量。
Is there a way to assign a random value to p1, p2, p3 and p4 for the following equation?
p1 y1 + p2 y2 + p3 y3 = p4
given that y1, y2 and y3 are variables to be solved.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最简单(?)的方法是在替换规则上
线程
随机值列表:例如:
或者,受Leonid的启发,您可以使用
Alternatives
和模式匹配:只是为了好玩,这里还有一个类似的解决方案:
如果您希望它不仅匹配
p0、p1、..,您可以将
.当然,对于大型表达式,上面的方法不会特别有效......DigitCharacter
替换为NumberString
。 ., p9The easiest(?) way is to
Thread
a list of random values over a replacement rule:For example:
Or, inspired by Leonid, you can use
Alternatives
and pattern matching:Just for fun, here's one more, similar solution:
Where you could replace
DigitCharacter
withNumberString
if you want it to match more than justp0, p1, ..., p9
. Of course, for large expressions, the above won't be particularly efficient...其他答案都很好,但是如果您做了很多此类事情,我建议以更系统的方式命名您的变量和系数。这不仅可以让您编写更简单的规则,还可以在从 3 个方程变为 4 个方程时进行更简单的更改。例如:
在创建方程时您可以有点奇特:
替换随机数系数现在是一个非常基本的规则:
最后的规则也可以写成
_p :>; RandomReal[]
,如果您愿意的话。您也不必输入太多内容来解决它。正如 Andrew Walker 所说,你使用 < code>Reduce 来查找所有解决方案,而不仅仅是其中的一些解决方案。您可以将其包装在一个参数化变量数量的函数中,如下所示:
The other answers are good, but if you do a lot of this sort of thing, I recommend naming your variables and coefficients in a more systematic way. This will not only allow you to write a much simpler rule, it will also make for much simpler changes when it's time to go from 3 equations to 4. For example:
You can be a little fancy when you make your equation:
Substituting random numbers for the coefficients is now one one very basic rule:
The rule at the end could also be written
_p :> RandomReal[]
, if you prefer. You don't have to type much to solve it, either.As Andrew Walker said, you use
Reduce
to find all the solutions, instead of just some of them. You can wrap this up in a function which paramerizes the number of variables like so:如果您需要代入值的解,一种可能的方法是:
如果您需要的只是方程的解:
If you need solutions with values substituted in, one possible way to do this is:
If all you need is the solution to the equations:
如果您可以在没有符号系数名称 p1 等的情况下生活,那么您可能会生成如下所示。我们采用变量列表、方程数量以及系数和 rhs 向量的范围。
获得整数系数、矩阵和 rhs 的不同范围等变体很简单。Daniel
Lichtblau
If you can live without the symbolic coefficient names p1 et al, then you might generate as below. We take a variable list, and number of equations, and a range for the coefficients and rhs vector.
It is straightforward to obtain variants such as integer coefficients, different ranges for matrix and rhs, etc.
Daniel Lichtblau
另一种方式:
Another way: