Product of polynomials. Introduction to Programming (in C++) Numerical algorithms. Product of polynomials. Product of polynomials

Similar documents
Approximate computations

Fig.25: the Role of LEX

cisc1110 fall 2010 lecture VI.2 call by value function parameters another call by value example:

Dynamic Programming. Andreas Klappenecker. [partially based on slides by Prof. Welch] Monday, September 24, 2012

2 Computing all Intersections of a Set of Segments Line Segment Intersection

P(r)dr = probability of generating a random number in the interval dr near r. For this probability idea to make sense we must have

box Boxes and Arrows 3 true 7.59 'X' An object is drawn as a box that contains its data members, for example:

Math 142, Exam 1 Information.

ZZ - Advanced Math Review 2017

Ma/CS 6b Class 1: Graph Recap

10.5 Graphing Quadratic Functions

Simplifying Algebra. Simplifying Algebra. Curriculum Ready.

1.5 Extrema and the Mean Value Theorem

In the last lecture, we discussed how valid tokens may be specified by regular expressions.

Ma/CS 6b Class 1: Graph Recap

COMPUTER SCIENCE 123. Foundations of Computer Science. 6. Tuples

Union-Find Problem. Using Arrays And Chains. A Set As A Tree. Result Of A Find Operation

Systems I. Logic Design I. Topics Digital logic Logic gates Simple combinational logic circuits

CIS 1068 Program Design and Abstraction Spring2015 Midterm Exam 1. Name SOLUTION

COMP 423 lecture 11 Jan. 28, 2008

Very sad code. Abstraction, List, & Cons. CS61A Lecture 7. Happier Code. Goals. Constructors. Constructors 6/29/2011. Selectors.

Introduction to Integration

Graphing Conic Sections

The Greedy Method. The Greedy Method

ASTs, Regex, Parsing, and Pretty Printing

Lecture 7: Integration Techniques

Slides for Data Mining by I. H. Witten and E. Frank

MATH 2530: WORKSHEET 7. x 2 y dz dy dx =

LING/C SC/PSYC 438/538. Lecture 21 Sandiway Fong

Section 10.4 Hyperbolas

Quiz2 45mins. Personal Number: Problem 1. (20pts) Here is an Table of Perl Regular Ex

Ray surface intersections

Solution of Linear Algebraic Equations using the Gauss-Jordan Method

What are suffix trees?

Orthogonal line segment intersection

MTH 146 Conics Supplement

Improper Integrals. October 4, 2017

Subtracting Fractions

Solving Problems by Searching. CS 486/686: Introduction to Artificial Intelligence Winter 2016

Information Retrieval and Organisation

What do all those bits mean now? Number Systems and Arithmetic. Introduction to Binary Numbers. Questions About Numbers

MA1008. Calculus and Linear Algebra for Engineers. Course Notes for Section B. Stephen Wills. Department of Mathematics. University College Cork

CS201 Discussion 10 DRAWTREE + TRIES

Compilers Spring 2013 PRACTICE Midterm Exam

Unit #9 : Definite Integral Properties, Fundamental Theorem of Calculus

What do all those bits mean now? Number Systems and Arithmetic. Introduction to Binary Numbers. Questions About Numbers

Representation of Numbers. Number Representation. Representation of Numbers. 32-bit Unsigned Integers 3/24/2014. Fixed point Integer Representation

such that the S i cover S, or equivalently S

9.1 apply the distance and midpoint formulas

CS 241. Fall 2017 Midterm Review Solutions. October 24, Bits and Bytes 1. 3 MIPS Assembler 6. 4 Regular Languages 7.

TO REGULAR EXPRESSIONS

CS311H: Discrete Mathematics. Graph Theory IV. A Non-planar Graph. Regions of a Planar Graph. Euler s Formula. Instructor: Işıl Dillig

The Fundamental Theorem of Calculus

If you are at the university, either physically or via the VPN, you can download the chapters of this book as PDFs.

Before We Begin. Introduction to Spatial Domain Filtering. Introduction to Digital Image Processing. Overview (1): Administrative Details (1):

George Boole. IT 3123 Hardware and Software Concepts. Switching Algebra. Boolean Functions. Boolean Functions. Truth Tables

CMPSC 470: Compiler Construction

Tries. Yufei Tao KAIST. April 9, Y. Tao, April 9, 2013 Tries

Alignment of Long Sequences. BMI/CS Spring 2012 Colin Dewey

Solving Problems by Searching. CS 486/686: Introduction to Artificial Intelligence

INTRODUCTION TO SIMPLICIAL COMPLEXES

CSCI1950 Z Computa4onal Methods for Biology Lecture 2. Ben Raphael January 26, hhp://cs.brown.edu/courses/csci1950 z/ Outline

Lecture Overview. Knowledge-based systems in Bioinformatics, 1MB602. Procedural abstraction. The sum procedure. Integration as a procedure

1 Quad-Edge Construction Operators

A Tautology Checker loosely related to Stålmarck s Algorithm by Martin Richards

Today. CS 188: Artificial Intelligence Fall Recap: Search. Example: Pancake Problem. Example: Pancake Problem. General Tree Search.

LU Decomposition. Mechanical Engineering Majors. Authors: Autar Kaw

Questions About Numbers. Number Systems and Arithmetic. Introduction to Binary Numbers. Negative Numbers?

CS 241 Week 4 Tutorial Solutions

Basics of Logic Design Arithmetic Logic Unit (ALU)

Lexical Analysis. Amitabha Sanyal. ( as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay

Section 5.3 : Finding Area Between Curves

CSc 453. Compilers and Systems Software. 4 : Lexical Analysis II. Department of Computer Science University of Arizona

Uninformed Search. Hal Daumé III. Computer Science University of Maryland CS 421: Introduction to Artificial Intelligence 31 Jan 2012

Mid-term exam. Scores. Fall term 2012 KAIST EE209 Programming Structures for EE. Thursday Oct 25, Student's name: Student ID:

Engineer To Engineer Note

Physics 208: Electricity and Magnetism Exam 1, Secs Feb IMPORTANT. Read these directions carefully:

EXPONENTIAL & POWER GRAPHS

Summer Review Packet For Algebra 2 CP/Honors

Agilent Mass Hunter Software

Implementing Automata. CSc 453. Compilers and Systems Software. 4 : Lexical Analysis II. Department of Computer Science University of Arizona

Approximation by NURBS with free knots

Pointers and Arrays. More Pointer Examples. Pointers CS 217

Control-Flow Analysis and Loop Detection

10/9/2012. Operator is an operation performed over data at runtime. Arithmetic, Logical, Comparison, Assignment, Etc. Operators have precedence

Agenda & Reading. Class Exercise. COMPSCI 105 SS 2012 Principles of Computer Science. Arrays

Section 3.1: Sequences and Series

Tree Structured Symmetrical Systems of Linear Equations and their Graphical Solution

If f(x, y) is a surface that lies above r(t), we can think about the area between the surface and the curve.

Lily Yen and Mogens Hansen

SIMPLIFYING ALGEBRA PASSPORT.

Math 464 Fall 2012 Notes on Marginal and Conditional Densities October 18, 2012

CSCI 104. Rafael Ferreira da Silva. Slides adapted from: Mark Redekopp and David Kempe

Math/CS 467/667 Programming Assignment 01. Adaptive Gauss Quadrature. q(x)p 4 (x) = 0

Matrices and Systems of Equations

PARALLEL AND DISTRIBUTED COMPUTING

COMBINATORIAL PATTERN MATCHING

Math 4 Review for Quarter 2 Cumulative Test

4/29/18 FIBONACCI NUMBERS GOLDEN RATIO, RECURRENCES. Fibonacci function. Fibonacci (Leonardo Pisano) ? Statue in Pisa Italy

Lecture 10 Evolutionary Computation: Evolution strategies and genetic programming

Transcription:

Product of polynomils Introduction to Progrmming (in C++) Numericl lgorithms Jordi Cortdell, Ricrd Gvldà, Fernndo Orejs Dept. of Computer Science, UPC Given two polynomils on one vrile nd rel coefficients, compute their product (we will decide lter how we represent polynomils) Exmple: given x 2 + 3x - 1 nd 2x - 5, otin 2x 3-5x 2 + 6x 2-15x - 2x + 5 = 2x 3 + x 2-17x + 5 Key point: Product of polynomils Given p(x) = n x n + n-1 x n-1 + + 1 x + 0 nd q(x) = m x m + m-1 x m-1 + + 1 x + 0, wht is the coefficient c i of x i in (p*q)(x)? Introduction to Progrmming Dept. CS, UPC 2 Product of polynomils Suppose we represent polynomil of degree n y vector of size n+1. Tht is, v[0..n] represents the polynomil v[n] x n + v[n-1] x n-1 + + v[1] x + v[0] We otin x i+j whenever we multiply i x i j x j Ide: for every i nd j, dd i j to the (i+j)-th coefficient of the product polynomil. We wnt to mke sure tht v[v.size() - 1] 0 so tht degree(v) = v.size() - 1 The only exception is the constnt-0 polynomil. We ll represent it y vector of size 0. Introduction to Progrmming Dept. CS, UPC 3 Introduction to Progrmming Dept. CS, UPC 4

Product of polynomils Product of polynomils Polynomil product(const Polynomil& p, const Polynomil& q) { typedef vector<doule> Polynomil; // Pre: -- // Returns p q Polynomil product(const Polynomil& p, const Polynomil& q); // Specil cse for polynomil of size 0 if (p.size() == 0 or q.size() == 0) return Polynomil(0); else { int deg = p.size() 1 + q.size() - 1; // degree of p q Polynomil r(deg + 1, 0); for (int i = 0; i < p.size(); ++i) { for (int j = 0; j < q.size(); ++j) { r[i + j] = r[i + j] + p[i] q[j]; return r; // Invrint (of the outer loop): r = product p[0..i-1] q // (we hve used the coefficients p[0] p[i-1]) Introduction to Progrmming Dept. CS, UPC 5 Sum of polynomils Note tht over the rel numers, degree(p q) = degree(p) + degree(q) (except if p = 0 or q = 0). So we know the size of the result vector from the strt. This is not true for the polynomil sum, e.g. Introduction to Progrmming Dept. CS, UPC 6 Sum of polynomils // Pre: -- // Returns p+q Polynomil sum(const Polynomil& p, const Polynomil& q); int mxdeg = mx(p.size(), q.size()) - 1; int deg = -1; Polynomil r(mxdeg + 1, 0); // Inv r[0..i-1] = (p+q)[0..i-1] nd // deg = lrgest j s.t. r[j]!= 0 (or -1 if none exists) for (int i = 0; i <= mxdeg; ++i) { if (i >= p.size()) r[i] = q[i]; else if (i >= q.size()) r[i] = p[i]; else r[i] = p[i] + q[i]; if (r[i]!= 0) deg = i; degree((x + 5) + (-x - 1)) = 0 Polynomil rr(deg + 1); for (int i = 0; i <= deg; ++i) rr[i] = r[i]; return rr; Introduction to Progrmming Dept. CS, UPC 7 Introduction to Progrmming Dept. CS, UPC 8

Sum of sprse vectors Sum of sprse vectors In some cses, prolems must del with sprse vectors or mtrices (most of the elements re zero). Sprse vectors nd mtrices cn e represented more efficiently y only storing the non-zero elements. For exmple, vector cn e represented s vector of pirs (index, vlue), sorted in scending order of the indices. Exmple: [0,0,1,0,-3,0,0,0,2,0,0,4,0,0,0] cn e represented s Design function tht clcultes the sum of two sprse vectors, where ech non-zero vlue is represented y pir (index, vlue): struct Pir { int index; int vlue; typedef vector<pir> SprseVector; [(2,1),(4,-3),(8,2),(11,4)] Introduction to Progrmming Dept. CS, UPC 9 Sum of sprse vectors Introduction to Progrmming Dept. CS, UPC 10 Sum of sprse vectors // Pre: -- // Returns v1+v2 SprseVector sprse_sum(const SprseVector& v1, const SprseVector& v2); // Inv: p1 nd p2 will point to the first // non-treted elements of v1 nd v2. // vsum contins the elements of v1+v2 treted so fr. // psum points to the first free loction in vsum. Strtegy: Clculte the sum on sufficiently lrge vector. Copy the result on nother vector of pproprite size. SprseVector sprse_sum(const SprseVector& v1, const SprseVector& v2) { SprseVector vsum; int p1 = 0, p2 = 0; while (p1 < v1.size() nd p2 < v2.size()) { if (v1[p1].index < v2[p2].index) { // Element only in v1 vsum.push_ck(v1[p1]); ++p1; else if (v1[p1].index > v2[p2].index) { // Element only in v2 vsum.push_ck(v2[p2]); ++p2; else { // Element in oth Pir p; p.index = v1[p1].index; p.vlue = v1[p1].vlue + v2[p2].vlue; if (p.vlue!= 0) vsum.push_ck(p); ++p1; ++p2; Introduction to Progrmming Dept. CS, UPC 11 Introduction to Progrmming Dept. CS, UPC 12

Sum of sprse vectors // Copy the remining elements of v1 while (p1 < v1.size()) { vsum.push_ck(v1[p1]); ++p1; Bolzno s theorem: Let f e rel-vlued continuous function. Let nd e two vlues such tht < nd f() f() < 0. Then, there is vlue c [,] such tht f(c)=0. // Copy the remining elements of v2 while (p2 < v2.size()) { vsum.push_ck(v2[p2]); ++p2; return vsum; c Introduction to Progrmming Dept. CS, UPC 13 Design function tht finds root of continuous function f in the intervl [, ] ssuming the conditions of Bolzno s theorem re fulfilled. Given precision ( ), the function must return vlue c such tht the root of f is in the intervl [c, c+ ]. Introduction to Progrmming Dept. CS, UPC 14 Strtegy: nrrow the intervl [, ] y hlf, checking whether the vlue of f in the middle of the intervl is positive or negtive. Iterte until the width of the intervl is smller. c Introduction to Progrmming Dept. CS, UPC 15 Introduction to Progrmming Dept. CS, UPC 16

// Pre: f is continuous, < nd f() f() < 0. // Returns c [,] such tht root exists in the // intervl [c,c+ ]. // Inv: root of f exists in the intervl [,] doule root(doule, doule, doule epsilon) { while ( > epsilon) { doule c = ( + )/2; if (f() f(c) <= 0) = c; else = c; return ; Introduction to Progrmming Dept. CS, UPC 17 // A recursive version doule root(doule, doule, doule epsilon) { if ( <= epsilon) return ; doule c = ( + )/2; if (f() f(c) <= 0) return root(,c,epsilon); else return root(c,,epsilon); Introduction to Progrmming Dept. CS, UPC 18 Brcode A rcode is n opticl mchine-redle representtion of dt. One of the most populr encoding systems is the UPC (Universl Product Code). A UPC code hs 12 digits. Optionlly, check digit cn e dded. Introduction to Progrmming Dept. CS, UPC 19 Introduction to Progrmming Dept. CS, UPC 20

Brcode Brcode The check digit is clculted s follows: 1. Add the digits in odd-numered positions (first, third, fifth, etc.) nd multiply y 3. 2. Add the digits in the even-numered positions (second, fourth, sixth, etc.) to the result. 3. Clculte the result modulo 10. 4. If the result is not zero, sutrct the result from 10. Exmple: 380006571113 (3+0+0+5+1+1) 3 = 30 8+0+6+7+1+3 = 25 (30+25) mod 10 = 5 10 5 = 5 Design progrm tht reds sequence of 12-digit numers tht represent UPCs without check digits nd writes the sme UPCs with the check digit. Question: do we need dt structure to store the UPCs? Answer: no, we only need few uxiliry vriles. Introduction to Progrmming Dept. CS, UPC 21 Brcode The progrm might hve loop treting UPC t ech itertion. The invrint could e s follows: // Inv: ll the UPCs of the treted codes // hve een written. At ech itertion, the progrm could red the UPC digits nd, t the sme time, write the UPC nd clculte the check digit. The invrint could e: // Inv: ll the treted digits hve een // written. The prtil clcultion of // the check digit hs een performed // sed on the treted digits. Introduction to Progrmming Dept. CS, UPC 22 Brcode // Pre: the input contins sequence of UPCs without check digits. // Post: the UPCs t the input hve een written with their check digits. int min() { chr c; while (cin >> c) { cout << c; int d = 3 (int(c) - int('0')); // first digit in n odd loction for (int i = 2; i <= 12; ++i) { cin >> c; cout << c; if (i%2 == 0) d = d + int(c) - int('0'); else d = d + 3 (int(c) - int('0')); d = d%10; if (d > 0) d = 10 d; cout << d << endl; Introduction to Progrmming Dept. CS, UPC 23 Introduction to Progrmming Dept. CS, UPC 24