digitalmars.D.learn - floating point divide
- Damian (8/8) Oct 11 2012 I come from a pascal background and we could use:
- Aziz K. (4/4) Oct 11 2012 int n1 = 10, n2 = 2;
- bearophile (14/22) Oct 11 2012 Two operators for the two different operations is a design better
- Damian (2/27) Oct 11 2012 Ah i see, thankyou for the explanation.
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));
Oct 11 2012
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.
Oct 11 2012
Damian:I come from a pascal background and we could use: div integral division operator / floating point division operatorTwo 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
Oct 11 2012
On Thursday, 11 October 2012 at 15:21:01 UTC, bearophile wrote:Damian:Ah i see, thankyou for the explanation.I come from a pascal background and we could use: div integral division operator / floating point division operatorTwo 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
Oct 11 2012