/******************************************************************************
* Compilation: javac Polynomial.java
* Execution: java Polynomial
*
* Polynomials with integer coefficients.
*
* % java Polynomial
* zero(x) = 0
* p(x) = 4x^3 + 3x^2 + 2x + 1
* q(x) = 3x^2 + 5
* p(x) + q(x) = 4x^3 + 6x^2 + 2x + 6
* p(x) * q(x) = 12x^5 + 9x^4 + 26x^3 + 18x^2 + 10x + 5
* p(q(x)) = 108x^6 + 567x^4 + 996x^2 + 586
* p(x) - p(x) = 0
* 0 - p(x) = -4x^3 - 3x^2 - 2x - 1
* p(3) = 142
* p'(x) = 12x^2 + 6x + 2
* p''(x) = 24x + 6
*
******************************************************************************/ package edu.princeton.cs.algs4; /**
* The {@code Polynomial} class represents a polynomial with integer
* coefficients.
* Polynomials are immutable: their values cannot be changed after they
* are created.
* It includes methods for addition, subtraction, multiplication, composition,
* differentiation, and evaluation.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/99scientific">Section 9.9</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Polynomial {
private int[] coef; // coefficients p(x) = sum { coef[i] * x^i }
private int degree; // degree of polynomial (-1 for the zero polynomial) /**
* Initializes a new polynomial a x^b
* @param a the leading coefficient
* @param b the exponent
* @throws IllegalArgumentException if {@code b} is negative
*/
public Polynomial(int a, int b) {
if (b < 0) {
throw new IllegalArgumentException("exponent cannot be negative: " + b);
}
coef = new int[b+1];
coef[b] = a;
reduce();
} // pre-compute the degree of the polynomial, in case of leading zero coefficients
// (that is, the length of the array need not relate to the degree of the polynomial)
private void reduce() {
degree = -1;
for (int i = coef.length - 1; i >= 0; i--) {
if (coef[i] != 0) {
degree = i;
return;
}
}
} /**
* Returns the degree of this polynomial.
* @return the degree of this polynomial, -1 for the zero polynomial.
*/
public int degree() {
return degree;
} /**
* Returns the sum of this polynomial and the specified polynomial.
*
* @param that the other polynomial
* @return the polynomial whose value is {@code (this(x) + that(x))}
*/
public Polynomial plus(Polynomial that) {
Polynomial poly = new Polynomial(0, Math.max(this.degree, that.degree));
for (int i = 0; i <= this.degree; i++) poly.coef[i] += this.coef[i];
for (int i = 0; i <= that.degree; i++) poly.coef[i] += that.coef[i];
poly.reduce();
return poly;
} /**
* Returns the result of subtracting the specified polynomial
* from this polynomial.
*
* @param that the other polynomial
* @return the polynomial whose value is {@code (this(x) - that(x))}
*/
public Polynomial minus(Polynomial that) {
Polynomial poly = new Polynomial(0, Math.max(this.degree, that.degree));
for (int i = 0; i <= this.degree; i++) poly.coef[i] += this.coef[i];
for (int i = 0; i <= that.degree; i++) poly.coef[i] -= that.coef[i];
poly.reduce();
return poly;
} /**
* Returns the product of this polynomial and the specified polynomial.
* Takes time proportional to the product of the degrees.
* (Faster algorithms are known, e.g., via FFT.)
*
* @param that the other polynomial
* @return the polynomial whose value is {@code (this(x) * that(x))}
*/
public Polynomial times(Polynomial that) {
Polynomial poly = new Polynomial(0, this.degree + that.degree);
for (int i = 0; i <= this.degree; i++)
for (int j = 0; j <= that.degree; j++)
poly.coef[i+j] += (this.coef[i] * that.coef[j]);
poly.reduce();
return poly;
} /**
* Returns the composition of this polynomial and the specified
* polynomial.
* Takes time proportional to the product of the degrees.
* (Faster algorithms are known, e.g., via FFT.)
*
* @param that the other polynomial
* @return the polynomial whose value is {@code (this(that(x)))}
*/
public Polynomial compose(Polynomial that) {
Polynomial poly = new Polynomial(0, 0);
for (int i = this.degree; i >= 0; i--) {
Polynomial term = new Polynomial(this.coef[i], 0);
poly = term.plus(that.times(poly));
}
return poly;
} /**
* Compares this polynomial to the specified polynomial.
*
* @param other the other polynoimal
* @return {@code true} if this polynomial equals {@code other};
* {@code false} otherwise
*/
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
Polynomial that = (Polynomial) other;
if (this.degree != that.degree) return false;
for (int i = this.degree; i >= 0; i--)
if (this.coef[i] != that.coef[i]) return false;
return true;
} /**
* Returns the result of differentiating this polynomial.
*
* @return the polynomial whose value is {@code this'(x)}
*/
public Polynomial differentiate() {
if (degree == 0) return new Polynomial(0, 0);
Polynomial poly = new Polynomial(0, degree - 1);
poly.degree = degree - 1;
for (int i = 0; i < degree; i++)
poly.coef[i] = (i + 1) * coef[i + 1];
return poly;
} /**
* Returns the result of evaluating this polynomial at the point x.
*
* @param x the point at which to evaluate the polynomial
* @return the integer whose value is {@code (this(x))}
*/
public int evaluate(int x) {
int p = 0;
for (int i = degree; i >= 0; i--)
p = coef[i] + (x * p);
return p;
} /**
* Compares two polynomials by degree, breaking ties by coefficient of leading term.
*
* @param that the other point
* @return the value {@code 0} if this polynomial is equal to the argument
* polynomial (precisely when {@code equals()} returns {@code true});
* a negative integer if this polynomialt is less than the argument
* polynomial; and a positive integer if this polynomial is greater than the
* argument point
*/
public int compareTo(Polynomial that) {
if (this.degree < that.degree) return -1;
if (this.degree > that.degree) return +1;
for (int i = this.degree; i >= 0; i--) {
if (this.coef[i] < that.coef[i]) return -1;
if (this.coef[i] > that.coef[i]) return +1;
}
return 0;
} /**
* Return a string representation of this polynomial.
* @return a string representation of this polynomial in the format
* 4x^5 - 3x^2 + 11x + 5
*/
@Override
public String toString() {
if (degree == -1) return "0";
else if (degree == 0) return "" + coef[0];
else if (degree == 1) return coef[1] + "x + " + coef[0];
String s = coef[degree] + "x^" + degree;
for (int i = degree - 1; i >= 0; i--) {
if (coef[i] == 0) continue;
else if (coef[i] > 0) s = s + " + " + (coef[i]);
else if (coef[i] < 0) s = s + " - " + (-coef[i]);
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
} /**
* Unit tests the polynomial data type.
*
* @param args the command-line arguments (none)
*/
public static void main(String[] args) {
Polynomial zero = new Polynomial(0, 0); Polynomial p1 = new Polynomial(4, 3);
Polynomial p2 = new Polynomial(3, 2);
Polynomial p3 = new Polynomial(1, 0);
Polynomial p4 = new Polynomial(2, 1);
Polynomial p = p1.plus(p2).plus(p3).plus(p4); // 4x^3 + 3x^2 + 1 Polynomial q1 = new Polynomial(3, 2);
Polynomial q2 = new Polynomial(5, 0);
Polynomial q = q1.plus(q2); // 3x^2 + 5 Polynomial r = p.plus(q);
Polynomial s = p.times(q);
Polynomial t = p.compose(q);
Polynomial u = p.minus(p); StdOut.println("zero(x) = " + zero);
StdOut.println("p(x) = " + p);
StdOut.println("q(x) = " + q);
StdOut.println("p(x) + q(x) = " + r);
StdOut.println("p(x) * q(x) = " + s);
StdOut.println("p(q(x)) = " + t);
StdOut.println("p(x) - p(x) = " + u);
StdOut.println("0 - p(x) = " + zero.minus(p));
StdOut.println("p(3) = " + p.evaluate(3));
StdOut.println("p'(x) = " + p.differentiate());
StdOut.println("p''(x) = " + p.differentiate().differentiate());
}
} /******************************************************************************
* Copyright 2002-2018, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/

java 多项式的更多相关文章

  1. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  2. JAVA入门 第五周 1多项式

    1 多项式加法(5分) 题目内容: 一个多项式可以表达为x的各次幂与系数乘积的和,比如: 现在,你的程序要读入两个多项式,然后输出这两个多项式的和,也就是把对应的幂上的系数相加然后输出. 程序要处理的 ...

  3. 最小二乘法多项式拟合的Java实现

    背景 由项目中需要根据一些已有数据学习出一个y=ax+b的一元二项式,给定了x,y的一些样本数据,通过梯度下降或最小二乘法做多项式拟合得到a.b,解决该问题时,首先想到的是通过spark mllib去 ...

  4. Java 一维多项式计算

    求解Java一维多项式的通用方法 比如ax^4+bx^3+cx^2+dx+e 可以化为(((ax+b)x+c)x+d)x+e 那么观察规律可以将系数放到一个数组里num[e,d,c,b,a] publ ...

  5. 【Java例题】5.1 多项式计算

    1. 计算下列多项式的值. pn=an*x^n+...+a1*x+a0其中,"^"表示乘方. x.n以及ai(i=0,1,...,n-1)由键盘输入. package chapte ...

  6. 中国MOOC_零基础学Java语言_第5周 数组_1多项式加法

    第5周编程题 查看帮助 返回   第5周编程题 依照学术诚信条款,我保证此作业是本人独立完成的. 温馨提示: 1.本次作业属于Online Judge题目,提交后由系统即时判分. 2.学生可以在作业截 ...

  7. Java练习 SDUT-2504_多项式求和

    多项式求和 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 多项式描述如下: 1 - 1/2 + 1/3 - 1/4 + ...

  8. Java实现 洛谷 多项式输出

    题目描述 一元nn次多项式可用如下的表达式表示: 其中,a_ix^ia i ​ x i 称为ii次项,a_ia i ​ 称为ii次项的系数.给出一个一元多项式各项的次数和系数,请按照如下规定的格式要求 ...

  9. Java实现 蓝桥杯VIP 算法提高 棋盘多项式

      算法提高 棋盘多项式   时间限制:1.0s   内存限制:256.0MB 棋盘多项式 问题描述 八皇后问题是在棋盘上放皇后,互相不攻击,求方案.变换一下棋子,还可以有八车问题,八马问题,八兵问题 ...

随机推荐

  1. 【C++】清空一个C++栈的快速方法

    来源:https://stackoverflow.com/questions/40201711/how-can-i-clear-a-stack-in-c-efficiently/40201744 传统 ...

  2. 深入理解JAVA虚拟机原理之内存分配策略(二)

    更多Android高级架构进阶视频学习请点击:https://space.bilibili.com/474380680 1.对象优先在Eden分配 大多情况,对象在新生代Eden区分配.当Eden区没 ...

  3. 如何去实现一个运用于多平台的SDK ?

    开始要求实现一个SDk的时候,一脸懵逼,以前总是调别人的SDK暴露的接口与方法,现在自己去实现一个,可以用到各平台上,还是相当有难度的,经过大半月的研究还是有点眉目的,想在这里和大家分享一下鄙人简陋的 ...

  4. web 服务中上传文件大小控制

    参考文章:https://rensanning.iteye.com/blog/2388353 项目场景: Vue + Nginx + Java + Tomcat Nginx作为反向代理服务器,访问To ...

  5. 伪类checked

    困惑了好久的复选框自定义样式终于有了谜底,原来就是一个 :checked 伪类 他的意思就是 匹配任意被勾选/选中的radio(单选按钮),chexked(复选框),或者option(select项) ...

  6. Linux操作系统 和 Windows操作系统 的区别

    针对这两个操作系统,下面是几点区别. 1.免费与收费 在中国, windows 和 linux 都是免费的,至少对个人用户是如此,如果哪天国内windows真的严打盗版了,那linux的春天就到了!但 ...

  7. Jquery中$.get(),$.post(),$.ajax(),$.getJSON(),$.getScript(),$.load()的用法总结

    参考文档 :  https://blog.csdn.net/jiandanokok/article/details/48809717 本文是对Jquery中$.get(),$.post(),$.aja ...

  8. 关于元素的offsetHeight、line-htight

    最近在做一个自适应高度的加载时的瀑布效果,使用加载完毕后为其一个A容器设置style的高度的方式完成(原高度为0且超出部分裁剪),使用offsetHeight获取其子元素高度(所有子元素高度均相等), ...

  9. mysql 两张表取总合 和差集

    SELECT id AS kid, NAME, IF (t1.kpi, t1.kpi, 0) AS kpi, t1.sort, STATUS, t1.kpi_idFROMform_kpi_nameLE ...

  10. 使用threading模块创建线程

    #_author:来童星#date:2019/12/17#使用threading模块创建线程import threading,timedef process(): for i in range(3): ...