Skip to content

Commit 2e900aa

Browse files
author
Lars Hartmann
committed
Fixing Division by zero error when sqrt((^2) + equals zero
1 parent 14462b1 commit 2e900aa

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/Sentiment/Vader.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,12 @@ public function isNegated(array $tokens, bool $includeNt = true) : bool
126126
*/
127127
public function normalize(float $score, int $alpha=15)
128128
{
129-
$normalizedScore = $score/sqrt(($score^2) + $alpha);
129+
$normalizedScore = $score;
130+
131+
if (sqrt(($score^2) + $alpha > 0)) {
132+
$normalizedScore = $score/sqrt(($score^2) + $alpha);
133+
}
134+
130135
if ($normalizedScore < -1.0) {
131136
return -1.0;
132137
} elseif ($normalizedScore > 1.0) {

tests/TextAnalysis/Sentiment/VaderTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,5 +128,28 @@ public function testSentimentScoreKindOfCombo()
128128

129129
$this->assertEquals(0.6197, $sentimentScores['compound']);
130130
}
131+
132+
public function testNormalizeZeroSum()
133+
{
134+
if( getenv('SKIP_TEST')) {
135+
return;
136+
}
137+
$tokens = [
138+
'If','the','Fake','News','Opposition','Party',
139+
'is','pushing','with','all','their','might',
140+
'the','fact','that','President','Trump',
141+
'“ignored','early','warnings','about',
142+
'the','threat','','then','why','did',
143+
'Media','&','Dems','viciously',
144+
'criticize','me','when','I',
145+
'instituted','a','Travel','Ban',
146+
'on','China','They','said',
147+
'“early','&','not','necessary.”','Corrupt','Media'
148+
];
149+
150+
$sentimentScores = vader($tokens);
151+
152+
$this->assertEquals(-1, $sentimentScores['compound']);
153+
}
131154

132155
}

0 commit comments

Comments
 (0)