1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use core::convert::TryFrom;
use core::ops::{AddAssign, Div, Mul, MulAssign, SubAssign};
use num::traits::{MulAddAssign, Pow};
use num::Zero;
use smallvec::SmallVec;

mod add;
mod display;
mod mul;
mod sub;
pub use add::*;
pub use display::*;
pub use mul::*;
pub use sub::*;

#[cfg(debug_assertions)]
macro_rules! assert_assume {
	($cond:expr) => {
		assert!($cond);
	};
	($cond:expr, $($arg:tt)+) => {
		assert!($cond, $($arg)+);
	};
}

#[cfg(not(debug_assertions))]
macro_rules! assert_assume {
	($cond:expr) => {
		if !($cond) {
			unsafe {
				std::hint::unreachable_unchecked();
				}
			}
	};
	($cond:expr, $($arg:tt)+) => {
		if !($cond) {
			unsafe {
				std::hint::unreachable_unchecked();
				}
			}
	};
}

#[macro_export]
macro_rules! coefficients {
	($elem:expr; $n:expr) => ({
		use smallvec::{smallvec, SmallVec};
		let ret : SmallVec<[_; 8]> = smallvec![$elem; $n];
		ret
	});
	($($x:expr),*$(,)*) => ({
		use smallvec::{smallvec, SmallVec};
		let ret : SmallVec<[_; 8]> = smallvec![$($x,)*];
		ret
	});
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Polynomial<T> {
	rev_coeffs: SmallVec<[T; 8]>,
}

impl<T> Polynomial<T> {
	pub fn order(&self) -> i32 {
		assert_assume!(!self.rev_coeffs.is_empty());
		assert_assume!(i32::try_from(self.rev_coeffs.len() - 1).is_ok());
		(self.rev_coeffs.len() - 1) as i32
	}

	pub fn reverse_coeffs(&self) -> &SmallVec<[T; 8]> {
		&self.rev_coeffs
	}

	pub fn into_coeffs(self) -> SmallVec<[T; 8]> {
		let mut coeffs = self.rev_coeffs;
		coeffs.reverse();
		coeffs
	}

	pub fn into_reverse_coeffs(self) -> SmallVec<[T; 8]> {
		self.rev_coeffs
	}

	pub fn coeffs(&self) -> SmallVec<[T; 8]>
	where
		T: Clone,
	{
		let mut coeffs = self.rev_coeffs.clone();
		coeffs.reverse();
		coeffs
	}

	fn fixup_coefficients(&mut self)
	where
		T: Zero,
	{
		while {
			if let Some(x) = self.rev_coeffs.last() {
				x.is_zero()
			} else {
				false
			}
		} {
			self.rev_coeffs.pop();
		}
		if self.rev_coeffs.is_empty() {
			self.rev_coeffs.push(T::zero());
		}
		assert!(i32::try_from(self.rev_coeffs.len() - 1).is_ok());
	}

	pub fn new(coefficients: SmallVec<[T; 8]>) -> Self
	where
		T: Zero,
	{
		let mut rev_coeffs = coefficients;
		rev_coeffs.reverse();
		Self::new_reversed(rev_coeffs)
	}

	pub fn new_reversed(rev_coeffs: SmallVec<[T; 8]>) -> Self
	where
		T: Zero,
	{
		let mut ret = Self { rev_coeffs };
		ret.fixup_coefficients();
		ret
	}

	pub fn eval<X, Y>(&self, x: X) -> Y
	where
		T: Zero,
		for<'l, 'r> &'l T: Mul<&'r X, Output = Y>,
		X: for<'r> MulAssign<&'r X> + num::One,
		Y: AddAssign + Zero,
	{
		let mut xn = X::one();
		let mut y = Y::zero();
		for a in self.rev_coeffs.iter() {
			y += a * &xn;
			xn *= &x;
		}
		y
	}

	pub fn eval_precise<X, Y>(&self, x: X) -> Y
	where
		T: Zero + Clone + Into<Y>,
		for<'l> &'l X: Pow<i32, Output = X>,
		Y: MulAddAssign<X, Y> + Zero,
		// this trait is only required to guide type inference
		for<'l> &'l T: Mul<X, Output = Y>,
	{
		let mut y = Y::zero();
		for (a, e) in self.rev_coeffs.iter().zip(0i32..) {
			// in num, MulAddAssign is only defined for values not references so we clone a
			let mut ay = a.clone().into();
			let mut y_old = Y::zero();
			core::mem::swap(&mut y, &mut y_old);
			ay.mul_add_assign(x.pow(e), y_old);
			core::mem::swap(&mut y, &mut ay);
		}
		y
	}

	pub fn eval_der<X, Y>(&self, x: X, n: i32) -> Y
	where
		T: Zero + num::FromPrimitive + for<'r> Mul<&'r X, Output = Y>,
		for<'l> &'l T: Mul<T, Output = T>,
		X: for<'r> MulAssign<&'r X> + num::One,
		Y: AddAssign + Zero,
	{
		assert!(n > 0);
		let mut xn = X::one();
		let mut y = Y::zero();
		for ((a, e_old), e_new) in self
			.rev_coeffs
			.iter()
			.zip(0i32..)
			.skip(n as usize)
			.zip(0i32..)
		{
			let mul = ((e_new + 1)..=e_old).product();
			y += (a * T::from_i32(mul).unwrap()) * &xn;
			xn *= &x;
		}
		y
	}

	pub fn eval_der_precise<X, Y>(&self, x: X, n: i32) -> Y
	where
		T: Zero + num::FromPrimitive + Into<Y>,
		for<'l> &'l T: Mul<T, Output = T>,
		for<'l> &'l X: Pow<i32, Output = X>,
		Y: MulAddAssign<X, Y> + Zero + Clone,
		// this trait is only required to guide type inference
		for<'l> &'l T: Mul<X, Output = Y>,
	{
		let mut y = Y::zero();
		for ((a, e_old), e_new) in self
			.rev_coeffs
			.iter()
			.zip(0i32..)
			.skip(n as usize)
			.zip(0i32..)
		{
			let mul = ((e_new + 1)..=e_old).product();
			let mut ay = (a * T::from_i32(mul).unwrap()).into();
			let mut y_old = Y::zero();
			core::mem::swap(&mut y, &mut y_old);
			ay.mul_add_assign(x.pow(e_new), y_old);
			core::mem::swap(&mut y, &mut ay);
		}
		y
	}

	pub fn div_rem(&self, rhs: &Self) -> (Self, Self)
	where
		T: Zero + Clone + for<'r> AddAssign<&'r T> + SubAssign,
		for<'l, 'r> &'l T: Mul<&'r T, Output = T> + Div<&'r T, Output = T>,
	{
		assert!(!rhs.is_zero());

		let order_l = self.order() as usize;
		let order_r = rhs.order() as usize;
		if order_l < order_r {
			return (Self::zero(), self.clone());
		}
		let order_o = order_l - order_r;

		let rhs = &rhs.rev_coeffs;
		let mut remainder = self.rev_coeffs.clone();
		let mut quotient = coefficients![T::zero(); order_o + 1];

		for el in (order_r..=order_l).rev() {
			let v = &remainder[el] / &rhs[order_r];
			remainder[el] = T::zero();
			for k in 1..=order_r {
				remainder[el - k] -= &v * &rhs[order_r - k];
			}
			quotient[el - order_r] = v;
		}

		(Self::new_reversed(quotient), Self::new_reversed(remainder))
	}
}

#[cfg(test)]
mod tests {
	use crate::*;

	#[cfg(not(debug_assertions))]
	use smallvec::SmallVec;

	#[test]
	fn test_new() {
		let poly = Polynomial::new(coefficients![0f32, 0.0, 1.0, 2.0, 3.0, 0.0]);
		assert_eq!(poly.order(), 3);
		let mut coeffs = coefficients![1f32, 2.0, 3.0, 0.0];
		assert_eq!(poly.coeffs(), coeffs);
		coeffs.reverse();
		assert_eq!(*poly.reverse_coeffs(), coeffs);
	}

	#[cfg(not(debug_assertions))]
	#[test]
	fn test_new_max_size() {
		let mut coefficients = SmallVec::new();
		coefficients.resize(
			usize::try_from(core::i32::MAX)
				.unwrap()
				.checked_add(1)
				.unwrap(),
			1u8,
		);
		let poly = Polynomial::new_reversed(coefficients);
		assert_eq!(poly.order(), core::i32::MAX);
	}

	#[cfg(not(debug_assertions))]
	#[test]
	#[should_panic(expected = "assertion failed: i32::try_from(self.rev_coeffs.len() - 1).is_ok()")]
	fn test_new_oversized() {
		let mut coefficients = SmallVec::new();
		coefficients.resize(
			usize::try_from(core::i32::MAX)
				.unwrap()
				.checked_add(2)
				.unwrap(),
			1u8,
		);
		Polynomial::new_reversed(coefficients);
	}

	#[test]
	fn test_eval() {
		let poly = Polynomial::new(coefficients![1f32, 2.0, 3.0, 0.0]);
		assert_eq!(poly.eval(2f32), 22.0);
		assert_eq!(
			poly.eval(num::Complex::new(0f32, 1.0)),
			num::Complex::new(-2f32, 2.0)
		);
		assert_eq!(poly.eval_precise(2f32), 22.0);
	}

	#[test]
	fn test_eval_substitution() {
		let mut poly = Polynomial::new(coefficients![1f32, 2.0, 3.0, 0.0]);
		poly = poly.eval(Polynomial::new(coefficients![1f32, 0.0, 0.0])); // x → x²
		assert_eq!(poly.order(), 6);
		assert_eq!(
			poly.into_coeffs(),
			coefficients![1f32, 0.0, 2.0, 0.0, 3.0, 0.0, 0.0]
		);
		poly = Polynomial::new(coefficients![1f32, 2.0, 3.0, 0.0]);
		poly = poly.eval(Polynomial::new(coefficients![1f32, 0.0, 1.0])); // x → x² + 1
		assert_eq!(
			poly.into_coeffs(),
			coefficients![1f32, 0.0, 5.0, 0.0, 10.0, 0.0, 6.0]
		);
	}

	#[test]
	fn test_eval_der() {
		// x³ + 2x² + 3x + 0
		let poly = Polynomial::new(coefficients![1f32, 2.0, 3.0, 0.0]);
		// 3x² + 4x + 3
		assert_eq!(poly.eval_der(0f32, 1), 3.0);
		assert_eq!(poly.eval_der(1f32, 1), 10.0);
		assert_eq!(poly.eval_der(2f32, 1), 23.0);
		assert_eq!(poly.eval_der_precise(0f32, 1), 3.0);
		assert_eq!(poly.eval_der_precise(1f32, 1), 10.0);
		assert_eq!(poly.eval_der_precise(2f32, 1), 23.0);
		// 6x + 4
		assert_eq!(poly.eval_der(0f32, 2), 4.0);
		assert_eq!(poly.eval_der(1f32, 2), 10.0);
		assert_eq!(poly.eval_der_precise(0f32, 2), 4.0);
		assert_eq!(poly.eval_der_precise(1f32, 2), 10.0);
	}

	#[test]
	fn test_div_rem() {
		let poly_a = Polynomial::new(coefficients![1f32, 2.0, 3.0, 0.0]);

		// (x³ + 2x² + 3x) / x = x² + 2x + 3 | 0
		let poly_b = Polynomial::new(coefficients![1f32, 0.0]);
		let (q, r) = poly_a.div_rem(&poly_b);
		assert_eq!(q.coeffs(), coefficients![1f32, 2.0, 3.0]);
		assert!(r.is_zero());

		// (x³ + 2x² + 3x) / 2x = 0.5x² + x + 1.5 | 0
		let poly_b = Polynomial::new(coefficients![2f32, 0.0]);
		let (q, r) = poly_a.div_rem(&poly_b);
		assert_eq!(q.coeffs(), coefficients![0.5f32, 1.0, 1.5]);
		assert!(r.is_zero());

		// (x³ + 2x² + 3x) / x² = x + 2 | 3x
		let poly_b = Polynomial::new(coefficients![1f32, 0.0, 0.0]);
		let (q, r) = poly_a.div_rem(&poly_b);
		assert_eq!(q.coeffs(), coefficients![1f32, 2.0]);
		assert_eq!(r.coeffs(), coefficients![3f32, 0.0]);

		// (x³ + 2x² + 3x) / (x² + 1) = x + 2 | 2x - 2
		let poly_b = Polynomial::new(coefficients![1f32, 0.0, 1.0]);
		let (q, r) = poly_a.div_rem(&poly_b);
		assert_eq!(q.coeffs(), coefficients![1f32, 2.0]);
		assert_eq!(r.coeffs(), coefficients![2f32, -2.0]);

		// (x² + 1) / (x³ + 2x² + 3x) = 0 | x² + 1
		let (q, r) = poly_b.div_rem(&poly_a);
		assert!(q.is_zero());
		assert_eq!(r, poly_b);
	}

	#[test]
	#[should_panic(expected = "assertion failed: !rhs.is_zero()")]
	fn test_div_rem_zero() {
		let poly_a = Polynomial::new(coefficients![1f32, 2.0, 3.0, 0.0]);
		let poly_b = Polynomial::zero();
		let _ = poly_a.div_rem(&poly_b);
	}
}