Implementing Sparse Vectors With Associative Arrays/Compiler Bug?

Nick B nick.barbalich at gmail.com
Sun Mar 10 00:07:32 PST 2013


On Thursday, 7 March 2013 at 07:03:04 UTC, Ed wrote:
> I'm new to D and am trying to implement simple sparse vectors 
> using associative arrays, but I'm getting fairly large floating 
> point errors. Example code for sparse dot product:
>
> import std.stdio;
> import std.math;
> import std.random;
> static import std.datetime;
>
> int main(string[] args) {
>   double[int] v1;
>   double[int] v2;
>   Random gen;
>   gen.seed(cast(uint)std.datetime.Clock.currTime().stdTime());
>
>   double accum = 0;
>   double val;
>   foreach(i;1 .. 1000) {
>     val = uniform(-1000.0,1000.0,gen);
>     accum += val * val;
>     v1[i] = val;
>     v2[i] = val;
>   }
>
>   double accum2 = 0;
>   double v2Val;
>   foreach(k;v1.byKey()) {
>     v2Val= v2.get(k,0);
>     if(v2Val != 0) {
>       accum2 += v1.get(k,0) * v2Val;
>     }
>   }
>
>   writefln("accum - accum2 = %e", accum - accum2);
>
>   return 0;
> }
>
> This outputs values such as:
> accum - accum2 = -4.172325e-07
> accum - accum2 = 2.384186e-07
> accum - accum2 = 4.172325e-07
>
> Are errors of this magnitude to be expected using doubles, or 
> is this a compiler bug?

Hi Ed

I also interested in simple sparse vectors.  Any chance this code 
could be published or put in a library ?

Nick


More information about the Digitalmars-d mailing list