Best way to code piecewise step function?

Feb 18, 2011 at 6:35am
Hello everyone,

Trying to code f(x) = [1 for 0<=t<1/2; -1 for 1/2<=t<1; 0 otherwise]. I wrote:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
int main()	
{
	double t, psi;
	t = 0.6; // example input
	psi = ( (t >= 0) && ( t < 0.5)? 1 : (t >= 0.5) && (t < 1) ? -1 : 0 );
	cout << psi;

	return 0;
}

this works fine, but I am not sure that's the fastest/least confusing way to do things. in particular is this what the ? operator was meant for? any input would be appreciated :)
Feb 18, 2011 at 6:59am
No, this is definitely not what is what made for. That's essentially obfuscated code, which takes quite a while to understand.

As opposed to that, it is obvious what the following does with just a glance:
1
2
3
if (t>=0 && t<0.5)psi=1;
else if (t>=0.5 && t<1)psi=-1;
else psi=0;


Feb 18, 2011 at 11:44am
The conditional operator works like this:

x?y:z
The outcome will equal y if x, and z otherwise.

Therefor:
1
2
3
4
5
6
7
( (t >= 0) && ( t < 0.5)? 1 : (t >= 0.5) && (t < 1) ? -1 : 0 )

( (t >= 0) && ( t < 0.5)?
     1 :
     (t >= 0.5) && (t < 1)?
          -1 :
          0 )
Can be read as:
If (t>=0) and (t<.5) return 1.
Else return (t>=0.5)&&(t<1)?-1:0
Last edited on Feb 18, 2011 at 11:45am
Feb 18, 2011 at 11:52am
Hey, Athar knows what the ternary operator is and does.

The point is that a nested mess like that is more likely to be misunderstood and buggy than a simple if..else if series.
Feb 19, 2011 at 6:55pm
Thanks guys! I got it :)
Topic archived. No new replies allowed.