Error with l2 normalization on a vector [Java] -


i'm trying use l2 normalization on double vector java.

double[] vector = {0.00423823948, 0.00000000000823285934, 0.0000342523505342, 0.000040240234023423, 0, 0}; 

now if use l2 normalization

for(double : vector){     squarevectorsum += * i; }  normalizationfactor = math.sqrt(squarevectorsum); // system.out.println(squarevectorsum+" "+normalizationfactor); for(int = 0; < vector.length; i++){     double normalizedfeature = vector[i] / normalizationfactor;     vector_result[i] = normalizedfeature; } 

my normalized vector this

normalized vector (l2 normalization) 0.9999222784309146 1.9423676996312713e-9 0.008081112110203743 0.009493825603572155 0.0 0.0 

now if if make squared sum of normalized-vector components should sum is equal one, instead squared sum

for(double : vector_result){     sum += i*i; } squared sum of normalized-vector 1.0000000000000004 

why sum not equal one? there problems in code? or it's because numbers small , there approximation doubles?

as indicated above, common issue, 1 you're going have deal if you're going use floating point binary arithmetic. problem crops when want compare 2 floating point binary numbers equality. since operations applied arrive @ values may not identical, neither binary representations.

there @ least couple strategies can consider deal situation. first involves comparing absolute difference between 2 floating point numbers, x , y rather strict equality , comparing them small value ϵ>0. like

if (math.abs(y-x) < epsilon) {     // assume x == y } else {     // assume x != y } 

this works when possible values of x , y have relatively tight bounding on exponents. when not case, value of x , y may such difference dominates ϵ choose (if exponent large) or ϵ dominates difference (such when possible exponents of x , y small). around this, instead of comparing absolute difference, instead compare ratio of x , y 1.0 , see whether ratio has absolute difference 1.0 more ϵ. like:

if (math.abs(x/y-1.0) < epsilon) {     // assume x == y } else {     // assume x != y } 

you need add check ensure y!=0 avoid division zero, that's general idea.

other options include using fixed point library java or rational number library java. have no recommendations that, though.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -