Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: Fix division by zero in linregress() for 2 data points #7007

Merged
merged 1 commit into from Feb 9, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 11 additions & 3 deletions scipy/stats/_stats_mstats_common.py
Expand Up @@ -103,11 +103,19 @@ def linregress(x, y=None):
r = -1.0

df = n - 2
t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY)))
prob = 2 * distributions.t.sf(np.abs(t), df)
slope = r_num / ssxm
intercept = ymean - slope*xmean
sterrest = np.sqrt((1 - r**2) * ssym / ssxm / df)
if n == 2:
# handle case when only two points are passed in
if y[0] == y[1]:
prob = 1.0
else:
prob = 0.0
sterrest = 0.0
else:
t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY)))
prob = 2 * distributions.t.sf(np.abs(t), df)
sterrest = np.sqrt((1 - r**2) * ssym / ssxm / df)

return LinregressResult(slope, intercept, r, prob, sterrest)

Expand Down
18 changes: 18 additions & 0 deletions scipy/stats/tests/test_stats.py
Expand Up @@ -873,6 +873,24 @@ def test_linregress_result_attributes(self):
attributes = ('slope', 'intercept', 'rvalue', 'pvalue', 'stderr')
check_named_results(res, attributes)

def test_regress_two_inputs(self):
# Regress a simple line formed by two points.
x = np.arange(2)
y = np.arange(3, 5)

res = stats.linregress(x, y)
assert_almost_equal(res[3], 0.0) # non-horizontal line
assert_almost_equal(res[4], 0.0) # zero stderr

def test_regress_two_inputs_horizontal_line(self):
# Regress a horizontal line formed by two points.
x = np.arange(2)
y = np.ones(2)

res = stats.linregress(x, y)
assert_almost_equal(res[3], 1.0) # horizontal line
assert_almost_equal(res[4], 0.0) # zero stderr

def test_nist_norris(self):
x = [0.2, 337.4, 118.2, 884.6, 10.1, 226.5, 666.3, 996.3, 448.6, 777.0,
558.2, 0.4, 0.6, 775.5, 666.9, 338.0, 447.5, 11.6, 556.0, 228.1,
Expand Down