How can I delete a random part of an expression?
Maybe, as a simple but general utility function, you can use this:
RandomDelete[expr_, pattern_, opts___] := Delete[
expr,
RandomChoice[Position[expr, pattern, opts]]
]
Then you can use it to randomly delete symbols:
RandomDelete[0.191575 (0.723501 + k - m^c)^(g z), _Symbol]
Or reals:
RandomDelete[0.191575 (0.723501 + k - m^c)^(g z), _Real]
And use the Heads
option that is used by Position
:
Table[RandomDelete[f[x, y], _, Heads -> False], 30]
I've added this to my Prototypes
paclet, available here:
PacletInstall["https://github.com/arnoudbuzing/prototypes/releases/download/v0.4.1/Prototypes-0.4.1.paclet"]
(And to uninstall, run PacletUninstall["Prototypes"]
)
Its documentation page has a few examples on how you can use it:
Clear@expr
expr=0.191575 (0.723501 + k - m^c)^(g z)
Delete[expr,RandomChoice@Position[expr, x_ /; Length@x == 0, Heads -> False]]
(*Original: 0.191575 (0.723501 +k-m^c)^(g z)
New: (0.723501 +k-m^c)^(g z)*)
deleteRandomCase = DeleteCases[#, RandomChoice[Cases[#, _Symbol | _Real, -1]], -1, 1] &;
Examples:
Table[deleteRandomCase[expr], {5}] // Column // TeXForm
$\begin{array}{l} 0.191575 \left(0.723501\, -m^c\right)^{g z} \\ 0.191575 \left(-m^c+k+0.723501\right)^g \\ \left(-m^c+k+0.723501\right)^{g z} \\ 0.191575 \left(k-m^c\right)^{g z} \\ 0.191575 \left(k-m^c\right)^{g z} \\ \end{array}$