A strange div bug on Linux x86_64, (both dmd & ldc2): long -5000 / size_t 2 = 9223372036854773308

jmh530 john.michael.hall at gmail.com
Thu Aug 13 11:40:59 UTC 2020


On Thursday, 13 August 2020 at 10:40:33 UTC, bachmeier wrote:
> 
> [snip]
>
> Imagine a new user to the language wanting to compute the mean 
> of an array of numbers:
>
> import std;
> void main()
> {
>     long sum = 0;
>     long[] vec = [-112, 2, 23, -4];
>     foreach(val; vec) {
>         sum += val;
>     }
>     writeln(sum/vec.length);
> }
>
> This is inexcusable.

It's certainly annoying, but if there were an equivalent length 
function in C, then it would have the same behavior. 
Unfortunately, this is one of those things that were carried over 
from C.

Also, note that the true mean of vec above is -22.75, which 
wouldn't even be the result of your function if length returned a 
signed variable, because you would be doing integer division. A 
person who comes to D without ever having programmed before would 
get tripped up by that too.

A new user to the language can use mir's mean function:
http://mir-algorithm.libmir.org/mir_math_stat.html#.mean

import mir.math.stat: mean;

void main()
{
     long[] vec = [-112, 2, 23, -4];
     assert(vec.mean == -22.75);
}


More information about the Digitalmars-d mailing list