Skip to content

Commit d8b5171

Browse files
ngtduc693Duc Nguyen
authored andcommitted
To handle floating-point precision issues in C#
1 parent 9a0b5f5 commit d8b5171

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

Algorithms/RecommenderSystem/CollaborativeFiltering.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ public double CalculateSimilarity(Dictionary<string, double> user1Ratings, Dicti
2929
double numerator = 0;
3030
double sumSquare1 = 0;
3131
double sumSquare2 = 0;
32+
double epsilon = 1e-10;
3233

3334
for (var i = 0; i < commonItems.Count; i++)
3435
{
@@ -41,7 +42,7 @@ public double CalculateSimilarity(Dictionary<string, double> user1Ratings, Dicti
4142
}
4243

4344
var denominator = Math.Sqrt(sumSquare1 * sumSquare2);
44-
return denominator == 0 ? 0 : numerator / denominator;
45+
return Math.Abs(denominator) < epsilon ? 0 : numerator / denominator;
4546
}
4647

4748
/// <summary>
@@ -62,6 +63,7 @@ public double PredictRating(string targetItem, string targetUser, Dictionary<str
6263
var targetUserRatings = ratings[targetUser];
6364
double totalSimilarity = 0;
6465
double weightedSum = 0;
66+
double epsilon = 1e-10;
6567

6668
foreach (var otherUser in ratings.Keys.Where(u => u != targetUser))
6769
{
@@ -74,7 +76,7 @@ public double PredictRating(string targetItem, string targetUser, Dictionary<str
7476
}
7577
}
7678

77-
return totalSimilarity == 0 ? 0 : weightedSum / totalSimilarity;
79+
return Math.Abs(totalSimilarity) < epsilon ? 0 : weightedSum / totalSimilarity;
7880
}
7981
}
8082
}

0 commit comments

Comments
 (0)