Implementing Sparse Vectors With Associative Arrays/Compiler Bug?
Ed
steveb at microsoft.com
Wed Mar 6 23:03:03 PST 2013
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?
More information about the Digitalmars-d
mailing list