Thread overview | ||||||
---|---|---|---|---|---|---|
|
October 11, 2012 floating point divide | ||||
---|---|---|---|---|
| ||||
I come from a pascal background and we could use: div integral division operator / floating point division operator So my question is, how does D force floating point division on integrals? At the moment i do this, but i was hoping for an easier way: int n1 = 10, n2 = 2; float f = cast(float)(cast(float)(n1 / n2)); |
October 11, 2012 Re: floating point divide | ||||
---|---|---|---|---|
| ||||
Posted in reply to Damian | int n1 = 10, n2 = 2; float f = (n1+0.0f)/n2; Casting n1 to float would also work, but I hope the compiler is smart enough to optimize away the plus expression. |
October 11, 2012 Re: floating point divide | ||||
---|---|---|---|---|
| ||||
Posted in reply to Damian | Damian: > I come from a pascal background and we could use: > div integral division operator > / floating point division operator Two operators for the two different operations is a design better than C, that is bug-prone. > So my question is, how does D force floating point division on integrals? > At the moment i do this, but i was hoping for an easier way: > > int n1 = 10, n2 = 2; > float f = cast(float)(cast(float)(n1 / n2)); That's not good, it performs an integer division, followed by two float casts. Note: float is useful only if you have many of them, or if you pass/return pairs of them. A single float is not so useful. A solution: int n1 = 10, n2 = 2; const f = n1 / cast(double)n2; Using type inference is useful, as it doesn't hide an integer result if your code is wrong. Bye, bearophile |
October 11, 2012 Re: floating point divide | ||||
---|---|---|---|---|
| ||||
Posted in reply to bearophile | On Thursday, 11 October 2012 at 15:21:01 UTC, bearophile wrote:
> Damian:
>
>> I come from a pascal background and we could use:
>> div integral division operator
>> / floating point division operator
>
> Two operators for the two different operations is a design better
> than C, that is bug-prone.
>
>
>> So my question is, how does D force floating point division on integrals?
>> At the moment i do this, but i was hoping for an easier way:
>>
>> int n1 = 10, n2 = 2;
>> float f = cast(float)(cast(float)(n1 / n2));
>
> That's not good, it performs an integer division, followed by two
> float casts.
>
> Note: float is useful only if you have many of them, or if you
> pass/return pairs of them. A single float is not so useful.
>
> A solution:
>
> int n1 = 10, n2 = 2;
> const f = n1 / cast(double)n2;
>
> Using type inference is useful, as it doesn't hide an integer
> result if your code is wrong.
>
> Bye,
> bearophile
Ah i see, thankyou for the explanation.
|
Copyright © 1999-2021 by the D Language Foundation