Skip to content

Commit 58cb31c

Browse files
committed
modify code following @andreasvarga recommendation
1 parent 6e71cb3 commit 58cb31c

File tree

3 files changed

+29
-6
lines changed

3 files changed

+29
-6
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name = "Polynomials"
22
uuid = "f27b6e38-b328-58d1-80ce-0feddd5e7a45"
33
license = "MIT"
44
author = "JuliaMath"
5-
version = "1.0.2"
5+
version = "1.0.3"
66

77
[deps]
88
Intervals = "d8418881-c3e1-53bb-8760-2df7ec849ed5"

docs/src/index.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,19 @@ ERROR: Polynomials must have same variable
101101
[...]
102102
```
103103

104+
Except for operations involving constant polynomials.
105+
106+
```jldoctest
107+
julia> p = Polynomial([1, 2, 3], :x)
108+
Polynomial(1 + 2*x + 3*x^2)
109+
110+
julia> q = Polynomial(1, :y)
111+
Polynomial(1)
112+
113+
julia> p+q
114+
Polynomial(2 + 2*x + 3*x^2)
115+
```
116+
104117
### Integrals and Derivatives
105118

106119
Integrate the polynomial `p` term by term, optionally adding constant

src/polynomials/Polynomial.jl

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ If ``p = a_n x^n + \\ldots + a_2 x^2 + a_1 x + a_0``, we construct this through
1111
1212
The usual arithmetic operators are overloaded to work with polynomials as well as
1313
with combinations of polynomials and scalars. However, operations involving two
14-
polynomials of different variables causes an error.
14+
polynomials of different variables causes an error except those involving a constant polynomial.
1515
1616
# Examples
1717
```@meta
@@ -85,14 +85,24 @@ function Base.:+(p1::Polynomial{T}, p2::Polynomial{S}) where {T, S}
8585
n1, n2 = length(p1), length(p2)
8686
if n1 > 1 && n2 > 1
8787
p1.var != p2.var && error("Polynomials must have same variable")
88-
c = [p1[i] + p2[i] for i = 0:max(n1, n2)]
89-
return Polynomial(c, p1.var)
88+
if n1 >= n2
89+
c = copy(p1.coeffs)
90+
for i = 1:n2
91+
c[i] += p2.coeffs[i]
92+
end
93+
else
94+
c = copy(p2.coeffs)
95+
for i = 1:n1
96+
c[i] += p1.coeffs[i]
97+
end
98+
end
99+
return Polynomial(c, p1.var)
90100
elseif n1 <= 1
91-
c = copy(p2.coeffs )
101+
c = copy(p2.coeffs)
92102
c[1] += p1[0]
93103
return Polynomial(c, p2.var)
94104
else
95-
c = copy(p1.coeffs )
105+
c = copy(p1.coeffs)
96106
c[1] += p2[0]
97107
return Polynomial(c, p1.var)
98108
end

0 commit comments

Comments
 (0)