/******************************************************************************
* 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. Ubuntu12.04下删除文件夹内所有的.svn文件

    前段时间在公司里遇到一个问题,从svn上下载下来的文件含有.svn文件,如何删除当前目录下的所有.svn文件呢? 一个个手动删除显然不可能,太多了.其实在Ubuntu12.04下延伸至其他所搜的Lin ...

  2. C# WinfForm 控件之dev图表 ChartControl

    dev 图表控件 学习连接 新建一个winformApp form1上放一个button 再放一个chartControl Name 为cct 直接上代码 private void button1_C ...

  3. 小程序onclick的写法?

    bindtap="bindAction" 调用bindAction函数即可

  4. Java生产环境下性能监控与调优详解

    1:JVM字节码指令与 javapjavap <options> <classes>cd monitor_tuning/target/classes/org/alanhou/m ...

  5. (Struts2学习系列二)Struts2动态方法调用:指定method属性

    紧接着上一篇,在HelloWorldAction.java中添加add和update方法: public class HelloWorldAction extends ActionSupport{ p ...

  6. tomcat之redis

    Nginx服务器:[root@nginx ~]# vim /usr/local/nginx/conf/nginx.confupstream tomcat_pool { server 192.168.2 ...

  7. linux 7下已有mysql之后,如何使用

    今天在使用阿里云平台的esc时,选择的centos7系统,在安装mariadb的时候,发现系统已经自带了,然后却无法使用,在调查了之后,发现启动service的依赖件没有安装,所以安装以下依赖件. m ...

  8. zero udp

    Description UDP transport can only be used with the ZMQ_RADIO and ZMQ_DISH socket types.

  9. 8.Struts2拦截器

    1. 拦截器的概述 * 拦截器就是AOP(Aspect-Oriented Programming)的一种实现.(AOP是指用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作.) * ...

  10. Go 动态类型声明

    Go 动态类型声明 package main import "fmt" func main() { var x float64 = 20.0 y := 42 fmt.Println ...