Sunteți pe pagina 1din 12

Math 182 (Introduction to Computer Programming)

Machine Exercises

Exercise 1
Problem: Calculate the solutions of the quadratic equation ax2 + bx + c = 0, where a, b
and c are real numbers.

Instructions

1. Write an algorithm or pseudocode that solves the problem above. The constants a, b,
and c are the inputs and the outputs are the solutions of the quadratic equation.

2. Use your algorithm to write a C++ script for the given problem. Your code should
do the following tasks:

(a) The variables a, b, and c are user input.


(b) If a = 0, then print the following warning message: Last input must be nonzero!
Program terminated.
(c) Display the quadratic equation based on the user input. For example, if a = 1,
b = 2 and c = −2, your code should print the following:

1x2 + 2x − 2 = 0

(d) Print the type of the solutions of the quadratic equation. Note that we only have
the following three possibilities: 2 real solutions, 1 real solution, or 2 complex
solutions

Include only the libraries <iostream> and <math.h>. Start your code with the following:

/*
Math 182 Machine Exercise 1
Authors: First_Name_1 Last_Name_1 and First_Name_2 Last_Name_2
Date: 30 August 2019
*/

Sample Dialogue 1:

Enter coefficients of quadratic equation starting at constant term:


1 -2 1

The equation 1x^2 - 2x + 1 = 0 has 1 real solution:


x = 1
Exercise 2
1. Fibonacci numbers
The Fibonacci numbers are defined through the following recursive sequence

f1 = 1, f2 = 1, fn = fn−1 + fn−2 for n ≥ 2.

Write a C++ code (with filename fibonacci.cpp) displaying the first N Fibonacci
numbers for a user input integer N . Use type int for N and type unsigned long for
the Fibonacci numbers. A sample dialogue is given below:

How many fibonacci numbers do you want? 4


1 1
2 1
3 2
4 3

If a Fibonacci number exceeds the maximum value for unsigned long integers, then
print the following after the last admissible Fibonacci number:

Maximum for unsigned long reached.

2. Calculating the sine using truncated Maclaurin series


Consider the following partial sum of the Maclaurin series expansion of the sine func-
tion
N
X x2n+1
sin x ≈ (−1)n .
(2n + 1)!
n=0

(a) Write an algorithm that approximates sin x for a user given value of x and N .
(b) Implement your algorithm and write a C++ code (and save using the file-
name sinefunction.cpp), wherein the above sum is calculated using a C++
user/programmer-defined function (use mysin as a function name) with the fol-
lowing declaration:
double mysin(double x, int N);
(c) Taking N = 100, discuss the limitation of the mysin function when calculating
the sine of a large number. From your observations, modify your algorithm and
create a new function (use modmysin as a function name) in order to circumvent
such limitations.
(d) In your main() function, display the values of sin x for x = ±1, ±10, ±100, ±1000,
with N = 100, using the modified sine function modmysin. Also, using the built-
in function sin in the library <math.h>, display the corresponding sine values
and calculate the absolute errors.

Include only the libraries <iostream>, <math.h> and <climits>. Start your code with the
following:

/*
Math 182 Machine Exercise 2
Authors: First_Name_1 Last_Name_1 and First_Name_2 Last_Name_2
Date: 24 September 2019
*/
Math 182 (Introduction to Computer Programming)
Machine Problem: An Extended Vector Class
Your task is to create a vector class to handle basic operations on elements of Rn . There
are two public data members, namely elements and size. The data member elements
consists of the components of the vector while size refers to the number of components. The
class definition has been provided. You need to fill the missing body statements (designated
by the three dots “...”) in the following functions and operators for the class. The desired
outputs are explained in detail below. Save the completed code as Vector.h. Use this as a
header file in another cpp code, that contains examples for all the functions and operators
involved in the class Vector.
#ifndef __VECTOR_H__
#define __VECTOR_H__

#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
using namespace std;

typedef unsigned int uint;

// Modified vector class to handle basic linear algebra operations.


template<typename T>
class Vector
{
public:
vector<T> elements;
uint size;

// Constructors
Vector();
Vector(uint);
Vector(vector<T>);
Vector(string);

// Print vector elements.


void print() const;

// Save vector to a text file with string filename as parameter.


void savetxt(string) const;

// Append element after the last entry.


void push_back(T value);

// Check if vector has same size to other vector.


bool has_equal_size(Vector<T>&) const;

// Retuns dot product.


double dot(Vector<T>&) const;

// Returns Euclidean norm.


double norm() const;
// Indexing operator.
T operator[] (uint);

// Comparison operator.
bool operator== (Vector<T>&);

// Destructor.
~Vector();
};

// Default constructor
template<typename T>
Vector<T>::Vector() {};

// Constructor for zero vector with size equal to the parameter num_elements.
template<typename T>
Vector<T>::Vector(uint num_elements){
...
}

// Constructor with vector data as parameter.


template<typename T>
Vector<T>::Vector(vector<T> data){
...
}

// Constructor with txt filename as parameter.


template<typename T>
Vector<T>::Vector(string filename){
...
}

// Print vector elements.


template<typename T>
void Vector<T>::print() const{
...
}

// Save vector elements to a txt file.


template<typename T>
void Vector<T>::savetxt(string filename) const{
...
}

// Check if vector has the same size as other parameter vector.


template<typename T>
bool Vector<T>::has_equal_size(Vector<T>& V) const{
...
}

// Dot product.
template<typename T>
double Vector<T>::dot(Vector<T>& V) const{
...
}

// Euclidean norm of vector.


template<typename T>
double Vector<T>::norm() const{
...
}

// Indexing operator.
template<typename T>
T Vector<T>::operator[] (uint index){
...
}

/*
Vector componentwise sum.
*/
template<typename T>
Vector<T> operator+ (Vector<T>& V, Vector<T>& W){
...
}

template<typename T>
Vector<T> operator+ (Vector<T>& V, T scalar){
...
}

template<typename T>
Vector<T> operator+ (T scalar, Vector<T>& V){
...
}

/*
Vector componentwise difference.
*/
template<typename T>
Vector<T> operator- (Vector<T>& V, Vector<T>& W){
...
}

template<typename T>
Vector<T> operator- (Vector<T>& V, T scalar){
...
}

template<typename T>
Vector<T> operator- (T scalar, Vector<T>& V){
...
}

/*
Vector componentwise multiplication.
*/
template<typename T>
Vector<T> operator* (Vector<T>& V, Vector<T>& W){
...
}

template<typename T>
Vector<T> operator* (Vector<T>& V, T scalar){
...
}

template<typename T>
Vector<T> operator* (T scalar, Vector<T>& V){
...
}

/*
Vector componentwise division.
*/
template<typename T>
Vector<T> operator/ (Vector<T>& V, Vector<T>& W){
...
}

template<typename T>
Vector<T> operator/ (Vector<T>& V, T scalar){
...
}

template<typename T>
void operator/ (T scalar, Vector<T>& V){
cout << "\nError: Operation not supported!" << endl;
}

// Vector push_back version.


template<typename T>
void Vector<T>::push_back(T value){
...
}

// Comparison operator.
template<typename T>
bool Vector<T>::operator== (Vector<T>& V){
...
}

// Default Destructor.
template<typename T>
Vector<T>::~Vector() {};

#endif
Math 182 (Introduction to Computer Programming)
Machine Problem: Matrix Class as an Extension to 2D Vector
Your task is to create a matrix class to handle basic linear algebra operations on ele-
ments of Rn×m . There are two public data members, namely elements and shape. The
data member elements consists of the components of the matrix while shape refers to the
corresponding dimension n × m. The class definition has been provided. You need to fill
the missing body statements (designated by the three dots “...”) in the following functions
and operators for the class. The desired outputs are explained in detail below. Save the
completed code as Matrix.h. Similar to the previous Machine Problem, use this as a header
file in another cpp code, that contains examples for all the functions and operators involved
in the class Matrix.

#ifndef __MATRIX_H__
#define __MATRIX_H__

#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include "Vector.h"
using namespace std;

typedef unsigned int uint;

// Matrix class to handle basic linear algebra operations.


template<typename T>
class Matrix
{
public:
vector<vector<T> > elements;
uint shape[2];

// Constructors
Matrix();
Matrix(uint, uint);
Matrix(vector<vector<T> >);
Matrix(string);

// Print vector elements.


void print() const;

// Print vector shape.


void printshape() const;

// Append a vector to the last row.


void push_back(vector<T>);

// Check if matrix has same shape to other matrix.


bool has_same_shape(Matrix<T>&) const;

// Save matrix to a text file with string filename as parameter.


void savetxt(string) const;
// Indexing operator that returns the row as a Vector class.
vector<T> operator[] (uint);

// Comparison operator.
bool operator== (Matrix<T>&);

// Matrix transpose.
Matrix<T> transpose();

// Destructor.
~Matrix();

};

// Default constructor.
template<typename T>
Matrix<T>::Matrix() {};

// Constructor for zero matrix with shape = num_row-by-num_col.


template<typename T>
Matrix<T>::Matrix(uint num_row, uint num_col){
...
}

// Constructor with 2d vector as parameter.


template<typename T>
Matrix<T>::Matrix(vector<vector<T> > data){
...
}

// Constructor with txt filename as parameter.


template<typename T>
Matrix<T>::Matrix(string filename){
...
}

// Print matrix elements.


template<typename T>
void Matrix<T>::print() const{
...
}

// Print matrix shape.


template<typename T>
void Matrix<T>::printshape() const{
...
}

// Save matrix elements to a txt file.


template<typename T>
void Matrix<T>::savetxt(string filename) const{
...
}
// Indexing operator.
template<typename T>
vector<T> Matrix<T>::operator[] (uint index){
...
}

// Matrix push_back version.


template<typename T>
void Matrix<T>::push_back(vector<T> v){
...
}

// Check if matrix has same shape to other matrix.


template<typename T>
bool Matrix<T>::has_same_shape(Matrix<T>& M) const{
...
}

// Comparison operator.
template<typename T>
bool Matrix<T>::operator== (Matrix<T>& M){
...
}

// Matrix transpose.
template<typename T>
Matrix<T> Matrix<T>::transpose(){
...
}

/*
Matrix componentwise sum.
*/
template<typename T>
Matrix<T> operator+ (Matrix<T>& M, Matrix<T>& N){
...
}

template<typename T>
Matrix<T> operator+ (Matrix<T>& M, T scalar){
...
}

template<typename T>
Matrix<T> operator+ (T scalar, Matrix<T>& M){
...
}

/*
Matrix componentwise difference.
*/
template<typename T>
Matrix<T> operator- (Matrix<T>& M, Matrix<T>& N){
...
}

template<typename T>
Matrix<T> operator- (Matrix<T>& M, T scalar){
...
}

template<typename T>
Matrix<T> operator- (T scalar, Matrix<T>& M){
...
}

/*
Matrix componentwise multiplication.
*/
template<typename T>
Matrix<T> operator* (Matrix<T>& M, Matrix<T>& N){
...
}

template<typename T>
Matrix<T> operator* (Matrix<T>& M, T scalar){
...
}

template<typename T>
Matrix<T> operator* (T scalar, Matrix<T>& M){
...
}

/*
Matrix componentwise division.
*/
template<typename T>
Matrix<T> operator/ (Matrix<T>& M, T scalar){
...
}

/*
Matrix-Vector product.
*/
template<typename T>
Vector<T> operator* (Matrix<T>& M, Vector<T>& V){
...
}

// Default destructor.
template<typename T>
Matrix<T>::~Matrix() {};

#endif
Math 182 (Introduction to Computer Programming)
Project
In computing the solution of partial differential equations on a convex polygonal domain,
for example using finite element or finite volume methods, the first step is to generate
a subdivision of the domain into smaller parts. Typical subdomains are triangles and
quadrilaterals. However, for domains with curved boundaries, it is more advantage and
often easier to provide a subdivision by using triangles.
Let D be a bounded convex polygonal domain on the plane R2 . A triangulation of D
is a collection T of triangles in D such that (1) the union of all triangles in T is D, and (2)
no vertex of any triangle in T lies in the interior or on an edge of another triangle.
Denote by
N = [(x0 , y0 ), (x1 , y1 ), . . . , (xn−1 , yn−1 )]
the list of coordinates of all distinct nodes of the triangles in a tringulation T of D. Then
we can represent
T = [∆0 , ∆1 , . . . , ∆m−1 ],
where m is the total number of triangles and for each k = 0, . . . , m − 1 we have

∆k = [ik1 , ik2 , ik3 ]

with (xik1 , yik1 ), (xik2 , yik2 ) and (xik3 , yik3 ) the coordinates of the vertices of the kth triangle
∆k . It should be noted that the triangles should have a fixed orientation.

For example, given the list of nodes

N = [(0, 0), (0, 1), (0.5, 0.5), (1, 0), (1, 1)]

we can represent the following triangulation as follows

T = [[0, 3, 2], [0, 2, 1], [2, 4, 1], [3, 4, 2]]

Figure 1: A Triangulation of the Unit Square


The accuracy of the numerical method depends on how fine and regular the triangulation
is. On one hand, we say that a triangulation is fine if the area of the largest triangle is
small, or equivalently, if the length of the largest edge in the triangulation is small.
One way to refine a given triangulation is via bisection. In this method, midpoints of
each edges in the triangulation are used to obtain new nodes. Then we replace each triangle
by new four triangles by connecting the edge midpoints.

Figure 2: Refinement of the triangulation by bisection.

1. Create a header file containing a mesh class along with its data members and member
functions. Your class should contain at least two data members, for example nodes
consisting of the coordinates of the nodes and triangles consisting of node indices
defining the triangles.

2. In your mesh class, create member functions that will refine the mesh. The returns of
these functions must correspond to new vectors corresponding to the nodes and node
connectivities of the refined mesh via bisection.

3. Use your header file in C++ code to bisect a triangulation of the unit square given by
the files node.txt and cell.txt as the data the members for nodes and triangles
in your class. Iterate the process by doing 1, 2, 3, 4, and 5 successive refinements.

4. Repeat the previous item, now for the circcell.txt and circnode.txt. Do a single
refinement only!

5. Present your algorithms in detail in the report and include the mesh plots obtained
from the python code plotmesh.py. Discuss your algorithms in detail as well as your
results.

S-ar putea să vă placă și