首页 > 解决方案 > 将表达式微分的结果添加到字符串变量

问题描述

我需要创建一个表达式差异列表(一阶、二阶等)并将结果打印到网格。

我正在尝试使用下一个代码(以及许多其他变体,但都是错误的)。我认为问题仅在于:ToString[D[z[x, y], {x, i - j}, {y, j}]]

MyFunction2[z_] := Block[ {x, y},
 arr = {{1, 1}, {1, 2, 1}, {1, 3, 3, 1}, {1, 4, 6, 4, 1}};
 result = {};
 For[i = 1, i <= 4, i++,
  res = "";
  For[j = 0, j <= i , j++,
   res = StringJoin[
    res,
    If[res == "", "", " + "], 
    If[arr[[i]][[j + 1]] > 1, 
    StringJoin[ToString[arr[[i]][[j + 1]]], "*"], ""],
    ToString[D[z[x, y], {x, i - j}, {y, j}]], 
    If[i - j > 0, "dx", ""],
    If[i - j > 1, StringJoin["^", ToString[ i - j]], ""], 
    If[j > 0, "dy", ""],
    If[j > 1, StringJoin["^", ToString[j]], ""]
   ];
  ];
  AppendTo[result, { StringJoin["d", If[i > 1, StringJoin["^", ToString[i]], ""], "z" ], res }];
   ];
  Grid[result, Frame -> All]
];
MyFunction2[Sin[x*y]]

我期待有这样的结果:

| dz | *yCos(xy)dx + xCos(xy)dy* |

但我得到的结果是: 带网格的图像

你能告诉我如何以人类可读的格式打印结果吗?

标签: wolfram-mathematica

解决方案


可能不完全是您正在寻找的,但应该很容易修改。

derivativeGrid[f_Function, xmax_Integer, ymax_Integer] := 
 Module[{derivatives, rowHeader, columnHeader, grid},
  derivatives = 
   Table[D[f[x, y], {x, i}, {y, j}], {i, 0, xmax}, {j, 0, ymax}];
  columnHeader = Table["dx"^x, {x, 0, xmax}];
  rowHeader = Join[{""}, Table["dy"^y, {y, 0, ymax}]];
  grid = MapThread[Prepend, {Prepend[derivatives, columnHeader], rowHeader}];
  Grid[grid, ItemStyle -> {{1 -> Bold}, {1 -> Bold}}, 
   Background -> {{LightYellow, None}, {LightYellow, None}}, 
   Frame -> All]]

因为它计算一个有两个参数的函数的导数f[x, y],所以它需要传递一个有两个参数的函数。

derivativeGrid[Sin[#1*#2] &, 3, 3]

在此处输入图像描述


推荐阅读