Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic number literals

Tags:

d

bool isUnit(Vec)(in Vec v, float tolerance = kindaSmallNumber){
    import std.math: abs;
    import std.conv: to;
    auto length = v.lengthSquared;
    return abs(to!(typeof(length))(1) - length) < tolerance;
}

Here I just want to calculate 1 - length but length could be of type double or float. I don't want to convert 1 from integer to float or double at runtime.

Do I have to do to!(typeof(length))(1) - length or can I just do 1 - length and 1 will always be of the same type as length?

like image 513
Maik Klein Avatar asked May 11 '26 16:05

Maik Klein


1 Answers

The type of 1 is irrelevant there. It will be automatically converted to an appropriate type for arithmetic with length.

From http://dlang.org/spec/expression.html#AddExpression

If either operand is a floating point type, the other is implicitly converted to floating point and they are brought to a common type via the usual arithmetic conversions.

So it is done automatically anyway by the compiler (which btw is known at compile time, of course, so it doesn't do any runtime stuff here).

But for other people who want to know the answer to the specific question, you could use typed literals like 1.0 or a type constructor, like typeof(length)(1).

like image 111
Adam D. Ruppe Avatar answered May 18 '26 17:05

Adam D. Ruppe