IsLinear

IsLinear

IsLinear[ expr, x ] checks if an expression is linear in a variable, and returns its slope and offset.

Usages

IsLinear[ expr, x ]

IsLinear[ expr, x ] checks whether expr can be written as slope·x + offset, where slope and offset do not depend on x. If so, the result is IsLinearResult[Slope=>slope, Offset=>offset]; otherwise the result is False. In a script, wrap the command in Simplify.

Example in out
A linear expression. Simplify[ IsLinear[3x + 2, x] ] IsLinearResult[Slope=>3, Offset=>2]
Other variables are allowed in the slope and offset. Simplify[ IsLinear[a x + b, x] ] IsLinearResult[Slope=>a, Offset=>b]
A fraction. Simplify[ IsLinear[(2x - 4)/3, x] ] IsLinearResult[Slope=>2/3, Offset=>-4/3]
Brackets are allowed. Simplify[ IsLinear[2(x + 1), x] ] IsLinearResult[Slope=>2, Offset=>2]
A constant has slope 0. Simplify[ IsLinear[5, x] ] IsLinearResult[Slope=>0, Offset=>5]
Not linear. Simplify[ IsLinear[x^2 + 1, x] ] False

Using the result

Use Type to check the result, and GetOption to get the slope and offset.

Example in out
Get the slope and offset. r := Simplify[IsLinear[3x + 2, x]]
s := GetOption[r, 'Slope']
o := GetOption[r, 'Offset']
s = 3
o = 2
Check whether the expression is linear. r := Simplify[IsLinear[3x + 2, x]]
If[Type[r] == IsLinearResult]
  t := 1
Else
  t := 0
End
t = 1
Details
  • Without Simplify, the command is not calculated.
  • The variable is required: Simplify[ IsLinear[3x + 2] ] is not calculated.
Warning

Do not check the result with r == False. For a linear expression, IsLinearResult[...] == False cannot be decided, so in an If it is treated as True. Use Type[r] == IsLinearResult, as in the example above.

See also: IsQuadratic, PolynomialDegree, Type, If