summaryrefslogtreecommitdiff
path: root/numpy/lib
diff options
context:
space:
mode:
authorStefan van der Walt <stefan@sun.ac.za>2007-08-06 12:42:58 +0000
committerStefan van der Walt <stefan@sun.ac.za>2007-08-06 12:42:58 +0000
commit5d4824522b29ac83d08d208723cba56ece1d6ea5 (patch)
tree2f8c9ef596b8321bbb4f65ce5d1807739d9db3ce /numpy/lib
parent7a605b4d18a7d5283c5c3eb31b9258150e5755c5 (diff)
downloadnumpy-5d4824522b29ac83d08d208723cba56ece1d6ea5.tar.gz
Fix string conversion of polynomial when leading coefficients are
zero. Closes ticket #564.
Diffstat (limited to 'numpy/lib')
-rw-r--r--numpy/lib/polynomial.py14
-rw-r--r--numpy/lib/tests/test_polynomial.py12
2 files changed, 21 insertions, 5 deletions
diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py
index 63ffec629..da1908d93 100644
--- a/numpy/lib/polynomial.py
+++ b/numpy/lib/polynomial.py
@@ -500,11 +500,15 @@ class poly1d(object):
return self.order
def __str__(self):
- N = self.order
thestr = "0"
var = self.variable
- for k in range(len(self.coeffs)):
- coefstr ='%.4g' % abs(self.coeffs[k])
+
+ # Remove leading zeros
+ coeffs = self.coeffs[NX.logical_or.accumulate(self.coeffs != 0)]
+ N = len(coeffs)-1
+
+ for k in range(len(coeffs)):
+ coefstr ='%.4g' % abs(coeffs[k])
if coefstr[-4:] == '0000':
coefstr = coefstr[:-5]
power = (N-k)
@@ -533,11 +537,11 @@ class poly1d(object):
if k > 0:
if newstr != '':
- if self.coeffs[k] < 0:
+ if coeffs[k] < 0:
thestr = "%s - %s" % (thestr, newstr)
else:
thestr = "%s + %s" % (thestr, newstr)
- elif (k == 0) and (newstr != '') and (self.coeffs[k] < 0):
+ elif (k == 0) and (newstr != '') and (coeffs[k] < 0):
thestr = "-%s" % (newstr,)
else:
thestr = newstr
diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py
index f3a8720d9..d7c2c917d 100644
--- a/numpy/lib/tests/test_polynomial.py
+++ b/numpy/lib/tests/test_polynomial.py
@@ -82,5 +82,17 @@ class test_docs(NumpyTestCase):
def check_roots(self):
assert_array_equal(N.roots([1,0,0]), [0,0])
+ def check_str_leading_zeros(self):
+ p = N.poly1d([4,3,2,1])
+ p[3] = 0
+ assert_equal(str(p),
+ " 2\n"
+ "3 x + 2 x + 1")
+
+ p = N.poly1d([1,2])
+ p[0] = 0
+ p[1] = 0
+ assert_equal(str(p), " \n0")
+
if __name__ == "__main__":
NumpyTest().run()