ifelse's strange perception of zero

Posted By: Sphin

ifelse's strange perception of zero - 11/04/15 00:20

Code:
function main() {
	var a = 1.0;
	var b = ifelse(a > 0, a, 0);
	printf("b = %.1f",b);
}

Result:
b = 1.0

Code:
function main() {
	var a = 0.9;
	var b = ifelse(a > 0, a, 0);
	printf("b = %.1f",b);
}

Result:
b = 0.0

means: 0.9 > 0 is not true. I spent hours to search for an error in my script ... laugh
Posted By: Florastamine

Re: ifelse's strange perception of zero - 11/04/15 09:01

printf() doesn't take var/float arguments. You need to explicitly cast it to double.

Code:
printf( "b = %.1f", (double) b );

Posted By: Sphin

Re: ifelse's strange perception of zero - 11/04/15 09:39

From the manual (printf/print/msg):

Quote:
For printing float variables with the %f placeholder, typecast them to (var).


For my variables are already declared as var I did not typecast them. What's right now?
Posted By: DdlV

Re: ifelse's strange perception of zero - 11/04/15 16:39

Hi Sphin,

I haven't tested, but a > 0.? On the assumption that your a > 0 is converting a to int before the comparison?

Regards.
Posted By: Sphin

Re: ifelse's strange perception of zero - 11/04/15 16:59

Oh my God ... I found the solution, thanks for the hint DdlV that drove me the right direction.

It is indeed the '0' in the comparism that converts a to an int. If this is not wanted you have to write:

var b = ifelse(a > 0, a, 0.); <- it is the '.' behind the 0 that makes the difference.

I actually need more time to get along with the programming language than to develop trading strategies ...
Posted By: jcl

Re: ifelse's strange perception of zero - 11/05/15 11:11

The "a > 0" should also be "a > 0.". It does not matter here, but it's better for always being on the safe side.

In a programming language, 0.9 is greater that 0.8, but it is not greater than 0 . When mixing integers and floats one must be very careful, so avoid mixing when possible. The compiler automatically converts different types, and mostly in the way that you want, but sometimes not.
Posted By: Sphin

Re: ifelse's strange perception of zero - 11/05/15 23:43

Strict distinction of the different types of variables and the consequences thereof are quite new for me switching from Perl to C.

Code:
Returns:
x when c is true, otherwise y. 
Remarks:
The returned variable type depends on the type of the arguments;[...]



Of course it's objectively right, but I thought if x is a var and y is an int then if c is true the returned variable is a var, otherwise it is an int. I never have guessed that the arguments themselves have been touched for conversion to either int or var.
© 2024 lite-C Forums