Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

How to define a function $f(x)$ such that $f(1.5)=1.5$, $f(1.)=1$, $f(0.)=0$, etc.? Namely, if $x$ is an integer with a decimal point, $f(x)$ returns the integer only, otherwise returns $x$.

This will be useful in the labels of the following plots.

Table[Block[{a = aa}, Show[Plot[x^a, {x, 0, 1}, PlotLabel -> Style[Row@{"a", "=", aa}, 15]]]], {aa, 0, 2, 0.5}]
share|improve this question
    
I actually just figured out an answer: f[x_] := If[Abs[FractionalPart[x]] < $MachineEpsilon, IntegerPart[x], x] –  renphysics Apr 12 at 13:02
2  
f[x_] := If[FractionalPart[x] == 0, IntegerPart[x], x] –  renphysics Apr 12 at 13:12

2 Answers 2

up vote 3 down vote accepted

There are numerous ways to accomplish what you're asking, but here's another way using a single definition:

f[x_]:=Piecewise[{{IntegerPart[x],x==IntegerPart[x]},{x,True}}]
share|improve this answer

I think the following definitions (you need both) will do want you're asking:

f[x_] := IntegerPart[x] /; x == IntegerPart[x]

f[x_] := x

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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