Well I assume that you want your script to do this:
1) Calculate $W and $D based on $X and $n (We will call this MakeNew()😉
2) Test and see if the values of $X, $W and $D match your criteria
3) If yes, then keep the values, if not, generate new ones.
So the basic code would be:
MakeNew();
while(($x<100000) && ($W != $D)) {
MakeNew();
}