3
$\begingroup$

Trying to create a rule to convert negative numbers/expressions positive.

So far:

f[-x_]:> f[x]

Trying to extend this rule to floats such as -1.0 and expressions like -x but am quite lost.

$\endgroup$
5
  • 5
    $\begingroup$ Does this work f[x_?Negative]:> -x? You can also do Sign[x] * x. That has the benefit of being faster if applied to a List of numbers $\endgroup$
    – b3m2a1
    Commented Feb 2, 2020 at 0:38
  • 2
    $\begingroup$ @b3m2a1 Sign[x] x is just Abs[x], of course. ;) $\endgroup$ Commented Feb 2, 2020 at 1:26
  • 1
    $\begingroup$ @J.M.isinlimbo -____- wow yes of course it is... $\endgroup$
    – b3m2a1
    Commented Feb 2, 2020 at 1:26
  • 1
    $\begingroup$ @J.M.isinlimbo that's not true for complex numbers though... $\endgroup$
    – Fraccalo
    Commented Feb 2, 2020 at 21:13
  • $\begingroup$ @Fraccalo, indeed, for complex numbers the relation becomes Sign[z] Abs[z] == z. $\endgroup$ Commented Feb 2, 2020 at 23:48

2 Answers 2

1
$\begingroup$

You can try it as a rule.

rule = {F[-x_] -> F[x], F[x_] -> F[Abs[x]]}

F[-5] /. rule
(*F[5]*)

F[-x] /. rule
(*F[x]*)

This may not cover all scenarios, but it includes yours.

$\endgroup$
0
$\begingroup$

An answer of poor quality:

f /: f[-x_] := -f[x]
f[x_ /; x < 0] := -x
f[-x]
f[-2]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.