Skip to content

Commit 82c9566

Browse files
author
Emmett Underhill
committed
Prevent divide by zero errors.
MetricLCS and NormalizedLevenshtein both divide by the max string length to produce distances. If two empty strings are used then a division by zero occurs and NaN is returned.
1 parent 6671ba2 commit 82c9566

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/main/java/info/debatty/java/stringsimilarity/MetricLCS.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,13 @@ public class MetricLCS
4747
* @return
4848
*/
4949
public final double distance(final String s1, final String s2) {
50+
int mLen = Math.max(s1.length(), s2.length());
51+
if (mLen == 0) {
52+
return 0;
53+
}
5054
return 1.0
5155
- (1.0 * lcs.length(s1, s2))
52-
/ Math.max(s1.length(), s2.length());
56+
/ mLen;
5357

5458
}
5559

src/main/java/info/debatty/java/stringsimilarity/NormalizedLevenshtein.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,11 @@ public class NormalizedLevenshtein implements
4848
* @return
4949
*/
5050
public final double distance(final String s1, final String s2) {
51-
return l.distance(s1, s2) / Math.max(s1.length(), s2.length());
51+
int mLen = Math.max(s1.length(), s2.length());
52+
if (mLen == 0) {
53+
return 0;
54+
}
55+
return l.distance(s1, s2) / mLen;
5256
}
5357

5458
/**

0 commit comments

Comments
 (0)