6
$\begingroup$

I realize this question has been asked many times, but I am fairly new at Mathematica and the other answers are very complex, and certainly too complicated for this simple code I am trying to write.

I want to restrict the function below to be between -1 and 1. I do not want to restrict the plot; I want to restrict the function itself.

f[x_] := -(x + c)^2

Is there a simple way I can do this?

$\endgroup$
5
11
$\begingroup$

I think the easiest way is to use Condition which has the operator form /;.

f[x_ /; -1 <= x <= 1, c_] := -(x + c)^2

Then

With[{c = -1/4}, Plot[f[x, c], {x, -2, 2}]]

plot

$\endgroup$
2
  • $\begingroup$ This worked! Thank you! $\endgroup$
    – Physika
    Jan 15 '18 at 23:45
  • 1
    $\begingroup$ @Physika consider also reading (1835) $\endgroup$
    – Mr.Wizard
    Jan 16 '18 at 7:40
4
$\begingroup$

Amplifying on m_goldberg's answer: The Condition can include a Message to use when the argument is outside the allowed interval.

ClearAll[f]

f::arg = "Argument value of `1` must be in the closed interval {-1, 1}.";

f[x_, c_] /; If[TrueQ[-1 <= x <= 1], True, Message[f::arg, x]] := -(x + c)^2

Then, an argument outside the interval generates a Message

f[2, c]

enter image description here

The Message can be turned Off

With[{c = -1/4}, Off[f::arg]; Plot[f[x, c], {x, -2, 2}]]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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