SlideShare a Scribd company logo
1 of 18
For any Homework related queries, Call us at : - +1 678 648 4277
You can mail us at : - info@cpphomeworkhelp.com or
reach us at : - https://www.cpphomeworkhelp.com/
Problem : Rational Number Library
Now that we know about the rounding issues of floating-point arithmetic, we’d like
to implement a library that will allow for exact computation with rational numbers.
This library should be easy and intuitive to use. You want to be able to write code as
straight-forward as you can see in this sample:
which produces the following as output.
auto a = Rational{ 1, 3 }; // the number 1/3
auto b = Rational{ -6, 7 }; // the number -6I7
std::cout «« "a * b = " «« a «« " * " «« b «« " = " «« a * b «« "n";
std::cout «« "a I ( a + b / a ) = " «« a / ( a + b / a ) «« "n";
a * b = 1I3 * -6I7 = -2/7
a / ( a + b / a ) = -7/47
Of course, we’ll be able to do much more impressive things. For example, here is
a snippet of code that computes the golden ratio ϕ to over 15 decimal digits of
accuracy using a very readable implementation of its continued fraction expansion.
cpphomeworkhelp.com
const int ITER = 40;
auto phi = Rational{ 1 }; II set equal to 1 to start off with
for( int i = 0; i « ITER; ++i ) {
phi = 1 I ( 1 + phi );
}
std::cout «« std::setprecision( 15 ); II look up «iomanip>
std::cout «« "phi = " «« ( 1 + phi ).to double() «« "n";
This prints out phi = 1.61803398874989, which happens to be 15 completely accurate
digits.
You can find the zipped project at provided in the file rational.zip as a basis for your
program. As in the other project problem, the folder contains an includeI directory,
our standard project Makefile, and a srcI directory. All of our header (.h) files will
be found in includeI while all of our source (.cpp) f iles will be in srcI. The C++
files you should find are rational.h, gcd.h, rational.cpp, gcd.cpp, and test.cpp; you
will be modifying rational.h and rational.cpp. Like in the previous project problem,
you can modify the Makefile or test.cpp to run your own tests, but your changes
there will be overwritten when you upload to the grader.
We are provided a header file describing the interface for the Rational class.
cpphomeworkhelp.com
#ifndef 6S096 RATIONAL H
#define 6S096 RATIONAL H
#include «cstdint>
#include «iosfwd>
#include «stdexcept>
class Rational {
intmax t num, den;
public:
enum sign type { POSITIVE, NEGATIVE };
Rational ( ) : num{0}, den{1} {}
Rational ( intmax t numer ) : num{numer}, den{1} {}
Rational ( intmax t numer, intmax t denom ) : num{numer}, den{denom} {
normalize(); // reduces the Rational to lowest terms
}
inline intmax t num() const { return num; }
inline intmax t den() const { return den; }
// you'll implement all these in rational.cpp
cpphomeworkhelp.com
void normalize( );
float to float() const;
double to double() const;
sign type sign() const;
Rational inverse() const;
};
// An example multiplication operator
inline Rational operator*( const Rational &a, const Rational &b ) {
return Rational{ a.num() * b.num(), a.den() * b.den() };
}
// Functions you'll be implementing:
std::ostream& operator««( std::ostream& os, const Rational &ratio );
// ... and so on
Notice the include guards at the top, protecting us from including the file multiple
times. An expla nation of some of the constructs we use is in order. You’ll notice
we use the intmax t type from the «cstdint> library. This type represents the
maximum width integer type for our particular architecture (basically, we want to
use the largest integers available). On my 64-bit computer, this means that we’lll
cpphomeworkhelp.com
f ind sizeof(Rational) to be 16 since it comprises two 64-bit (8-byte) integers.
Look up an enum. We use this to define a type sign type in the scope of our
class. Outside the class, we can refer to the type as Rational::sign type and its two
values as Rational::POSITIVE and Rational::NEGATIVE.
Contained in the header file is also a class that extends std::domain error to create
a special type of exception for our Rational class. Look up the meaning of explicit;
why do we use it in this particular constructor definition?
Read through the code carefully and make sure you understand it. If you have any
questions about the provided code or don’t know why something is structured the way it
is, please ask about it on Piazza.
This is the list of functions you should fill out. In the header file, you have a
number of inline functions to complete, as shown here.
#include <stdexcept>
// ...near the bottom of the file
class bad rational : public std::domain error {
public:
explicit bad rational() : std::domain error( "Bad rational: zero denom." ) {}
};
cpphomeworkhelp.com
inline Rational operator+( const Rational &a, const Rational &b ) {/* ... */}
inline Rational operator-( const Rational &a, const Rational &b ) {/* ... */}
inline Rational operatorI( const Rational &a, const Rational &b ) {/* ... */}
inline bool operator«( const Rational &lhs, const Rational &rhs ) {/* ... */}
inline bool operator==( const Rational &lhs, const Rational &rhs ) {/* ... */}
There are also a number of functions declared in the header file which you
should write an implemeatation for in the source file rational.cpp. Those declarations
are:
class Rational {
// ...snipped
public:
// ...snipped
void normalize();
float to float() const;
double to double() const;
sign type sign() const;
};
std::ostream& operator««( std::ostream& os, const Rational &ratio );
cpphomeworkhelp.com
Look in the existing rational.cpp file for extensive descriptions of the required
functionality. In gcd.h, you can find the declaration for two functions which you
may find useful: fast computation of the greatest common divisor and least
common multiple of two integers. Feel free to include this header and use these
functions in your code as needed.
#ifndef 6S096 GCD H
#define 6S096 GCD H
#include «cstdint>
intmax t gcd( intmax t a,
intmax t b ); intmax t lcm( intmax t a, intmax t b );
#endif // 6S096 GCD H
Input Format
Not applicable; your library will be compiled into a testing suite, your
implemented functions will be called by the program, and the behavior checked
for correctness. For example, here is a potential test:
cpphomeworkhelp.com
#include "rational.h"
#include «cassert>
void test addition() {
// Let's try adding 1/3 + 2/15 = 7/15.
auto sum = Rational{ 1, 3 } + Rational{ 2, 15 }
assert( sum.num() == 7 );
assert( sum.den() == 15 );
}
You are strongly encouraged to write your own tests in test.cpp so that you can
try out your imple mentation code before submitting it to the online grader.
Output Format
Not applicable.
cpphomeworkhelp.com
Code : Rational Number Library
#ifndef _6S096_RATIONAL_H
#define _6S096_RATIONAL_H
#include <cstdint>
#include <iosfwd>
#include <stdexcept>
class Rational {
intmax_t _num, _den;
public:
enum sign_type { POSITIVE, NEGATIVE };
Rational() : _num{0}, _den{1} {}
Rational( intmax_t numer ) : _num{numer}, _den{1} {}
Rational( intmax_t numer, intmax_t denom ) : _num{numer}, _den{denom} { normalize(); }
inline intmax_t num() const { return _num; }
inline intmax_t den() const { return _den; }
void normalize();
float to_float()const;
cpphomeworkhelp.com
double to_double()const;
sign_type sign() const;
Rational inverse() const;
};
std::ostream& operator<<( std::ostream& os, const Rational &ratio );
inline bool operator==( const Rational &lhs, const Rational &rhs ) { return lhs.num() *
rhs.den() == rhs.num() * lhs.den();
}
inline bool operator<( const Rational &lhs, const Rational &rhs ) {
if( lhs.sign() == Rational::POSITIVE && rhs.sign() == Rational::POSITIVE ) {
return lhs.num() * rhs.den() < rhs.num() * lhs.den();
} else if( lhs.sign() == Rational::NEGATIVE && rhs.sign() == Rational::NEGATIVE ) {
return lhs.num() * rhs.den() > rhs.num() * lhs.den();
} else {
return lhs.sign() == Rational::NEGATIVE;
}
}
inline Rational operator*( const Rational &a, const Rational &b ) {
return Rational{ a.num() * b.num(), a.den() * b.den() };
}
cpphomeworkhelp.com
inline Rational operator+( const Rational &a, const Rational &b ) {
return Rational{ a.num() * b.den() + b.num() * a.den(), a.den() * b.den() };
}
inline Rational operator-( const Rational &a, const Rational &b ) {
return Rational{ a.num() * b.den() - b.num() * a.den(), a.den() * b.den() };
}
inline Rational operator/( const Rational &a, const Rational &b ) {
return a * b.inverse();
}
class bad_rational : public std::domain_error {
public:
explicit bad_rational() : std::domain_error("Bad rational: zero denominator" ) {}
};
#endif // _6S096_RATIONAL_H
Here is the source code file rational.cpp:
#include "rational.h"
#include "gcd.h"
#include <stdexcept>
#include <ostream>
#include <iostream>
#include <cmath> cpphomeworkhelp.com
Rational Rational::inverse() const {
return Rational{ _den, _num };
}
Rational::sign_type Rational::sign()const {
return _num >= 0 ? POSITIVE : NEGATIVE;
}
std::ostream& operator<<( std::ostream& os, const Rational &ratio ) {
if( ratio == 0 ) {
os << "0";
} else {
if( ratio.sign() == Rational::NEGATIVE ) {
os << "-";
}
os << std::abs( ratio.num() ) << "/" << std::abs( ratio.den() );
}
return os;
}
void Rational::normalize() {
if( _den == 0 ) {
throw bad_rational();
} if( _num == 0 ) {
_den = 1; return;
}
cpphomeworkhelp.com
auto g = gcd( std::abs( _num ), std::abs( _den ) );
_num /= g; _den /= g;
if( _den < 0 ) {
_num = -_num;
_den = -_den;
}
}
float Rational::to_float() const {
return static_cast<float>( _num ) / static_cast<float>( _den );
}
double Rational::to_double()const {
return static_cast<double>( _num ) / static_cast<double>( _den );
}
Below is the output using the test data:
rational:
1: OK [0.007 seconds] OK! add
2: OK [0.006 seconds] OK! mult
3: OK [0.009 seconds] OK! add1024
4: OK [0.014 seconds] OK! add1024
cpphomeworkhelp.com
5: OK [0.158 seconds] OK! add32768
6: OK [0.007 seconds] OK! op<<
7: OK [0.289 seconds] OK! div65536 in 0.280000 s
8: OK [0.006 seconds] OK! phi, 0.000000e+00
9: OK [0.006 seconds] OK! (Bad rational: zero denominator)
10: OK [0.006 seconds] OK! xyz
11: OK [0.007 seconds] OK! pow2
12: OK [0.006 seconds] OK! X1z
#ifndef _6S096_GCD_H
#define _6S096_GCD_H
#include <cstdint>
intmax_t gcd( intmax_t a, intmax_t b );
intmax_t lcm( intmax_t a, intmax_t b );
#endif // _6S096_GCD_H
#ifndef _6S096_RATIONAL_H
#define _6S096_RATIONAL_H
#include <cstdint>
#include <iosfwd>
#include <stdexcept> cpphomeworkhelp.com
class Rational {
intmax_t _num, _den;
public:
enum sign_type { POSITIVE, NEGATIVE };
Rational() : _num{0}, _den{1} {}
Rational( intmax_t numer ) : _num{numer}, _den{1} {}
Rational( intmax_t numer, intmax_t denom ) : _num{numer}, _den{denom} {
normalize(); }
inline intmax_t num() const { return _num; }
inline intmax_t den() const { return _den; }
// You should implement all of these functions in rational.cpp
void normalize();
float to_float() const;
double to_double() const;
sign_type sign() const;
const Rational inverse() const;
};
std::ostream& operator<<( std::ostream &os, const Rational &ratio );
cpphomeworkhelp.com
inline bool operator==( const Rational &lhs, const Rational &rhs ) {
// You should implement
}
inline bool operator<( const Rational &lhs, const Rational &rhs ) {
// You should implement
}
// This one is completed for you. We multiply two Rationals
// by creating a new Rational as shown:
//
// a.num() b.num() a.num() * b.num()
// ------- * ------- = -----------------
// a.den() b.den() a.den() * b.den()
//
// Our constructor should automatically reduce it to lowest terms,
// e.g. 1/2 * 2/3 = 1/3 automatically.
inline Rational operator*( const Rational &a, const Rational &b ) {
return Rational{ a.num() * b.num(), a.den() * b.den() };
}
inline Rational operator+( const Rational &a, const Rational &b ) {
// You should implement
}
cpphomeworkhelp.com
inline Rational operator-( const Rational &a, const Rational &b ) {
// You should implement
}
inline Rational operator/( const Rational &a, const Rational &b ) {
// You should implement
}
class bad_rational : public std::domain_error {
public:
explicit bad_rational() : std::domain_error( "Bad rational: zero denominator" ) {}
};
#endif // _6S096_RATIONAL_H
cpphomeworkhelp.com

More Related Content

What's hot (19)

Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
 
C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
C++
C++C++
C++
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Data types in c++
Data types in c++ Data types in c++
Data types in c++
 

Similar to Rational Number Library Implementation

OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++cpjcollege
 
(Rational Class) - use the original files to create the new progra.pdf
(Rational Class) - use the original files to create the new progra.pdf(Rational Class) - use the original files to create the new progra.pdf
(Rational Class) - use the original files to create the new progra.pdfalstradecentreerode
 
C BASICS.pptx FFDJF/,DKFF90DF SDPJKFJ[DSSIFLHDSHF
C BASICS.pptx FFDJF/,DKFF90DF SDPJKFJ[DSSIFLHDSHFC BASICS.pptx FFDJF/,DKFF90DF SDPJKFJ[DSSIFLHDSHF
C BASICS.pptx FFDJF/,DKFF90DF SDPJKFJ[DSSIFLHDSHFAbcdR5
 
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...bhargavi804095
 
C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxfaithxdunce63732
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdfexxonzone
 

Similar to Rational Number Library Implementation (20)

Computer Science Assignment Help
 Computer Science Assignment Help  Computer Science Assignment Help
Computer Science Assignment Help
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
CPP Assignment Help
CPP Assignment HelpCPP Assignment Help
CPP Assignment Help
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 
(Rational Class) - use the original files to create the new progra.pdf
(Rational Class) - use the original files to create the new progra.pdf(Rational Class) - use the original files to create the new progra.pdf
(Rational Class) - use the original files to create the new progra.pdf
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
C BASICS.pptx FFDJF/,DKFF90DF SDPJKFJ[DSSIFLHDSHF
C BASICS.pptx FFDJF/,DKFF90DF SDPJKFJ[DSSIFLHDSHFC BASICS.pptx FFDJF/,DKFF90DF SDPJKFJ[DSSIFLHDSHF
C BASICS.pptx FFDJF/,DKFF90DF SDPJKFJ[DSSIFLHDSHF
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
How c/c++ works
How c/c++ worksHow c/c++ works
How c/c++ works
 
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
C language tutorial
C language tutorialC language tutorial
C language tutorial
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
 

More from C++ Homework Help (18)

cpp promo ppt.pptx
cpp promo ppt.pptxcpp promo ppt.pptx
cpp promo ppt.pptx
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
 
CPP Programming Homework Help
CPP Programming Homework HelpCPP Programming Homework Help
CPP Programming Homework Help
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
Online CPP Homework Help
Online CPP Homework HelpOnline CPP Homework Help
Online CPP Homework Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
Get Fast C++ Homework Help
Get Fast C++ Homework HelpGet Fast C++ Homework Help
Get Fast C++ Homework Help
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Online CPP Homework Help
Online CPP Homework HelpOnline CPP Homework Help
Online CPP Homework Help
 
CPP Homework help
CPP Homework helpCPP Homework help
CPP Homework help
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
 

Recently uploaded

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 

Recently uploaded (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 

Rational Number Library Implementation

  • 1. For any Homework related queries, Call us at : - +1 678 648 4277 You can mail us at : - info@cpphomeworkhelp.com or reach us at : - https://www.cpphomeworkhelp.com/
  • 2. Problem : Rational Number Library Now that we know about the rounding issues of floating-point arithmetic, we’d like to implement a library that will allow for exact computation with rational numbers. This library should be easy and intuitive to use. You want to be able to write code as straight-forward as you can see in this sample: which produces the following as output. auto a = Rational{ 1, 3 }; // the number 1/3 auto b = Rational{ -6, 7 }; // the number -6I7 std::cout «« "a * b = " «« a «« " * " «« b «« " = " «« a * b «« "n"; std::cout «« "a I ( a + b / a ) = " «« a / ( a + b / a ) «« "n"; a * b = 1I3 * -6I7 = -2/7 a / ( a + b / a ) = -7/47 Of course, we’ll be able to do much more impressive things. For example, here is a snippet of code that computes the golden ratio ϕ to over 15 decimal digits of accuracy using a very readable implementation of its continued fraction expansion. cpphomeworkhelp.com
  • 3. const int ITER = 40; auto phi = Rational{ 1 }; II set equal to 1 to start off with for( int i = 0; i « ITER; ++i ) { phi = 1 I ( 1 + phi ); } std::cout «« std::setprecision( 15 ); II look up «iomanip> std::cout «« "phi = " «« ( 1 + phi ).to double() «« "n"; This prints out phi = 1.61803398874989, which happens to be 15 completely accurate digits. You can find the zipped project at provided in the file rational.zip as a basis for your program. As in the other project problem, the folder contains an includeI directory, our standard project Makefile, and a srcI directory. All of our header (.h) files will be found in includeI while all of our source (.cpp) f iles will be in srcI. The C++ files you should find are rational.h, gcd.h, rational.cpp, gcd.cpp, and test.cpp; you will be modifying rational.h and rational.cpp. Like in the previous project problem, you can modify the Makefile or test.cpp to run your own tests, but your changes there will be overwritten when you upload to the grader. We are provided a header file describing the interface for the Rational class. cpphomeworkhelp.com
  • 4. #ifndef 6S096 RATIONAL H #define 6S096 RATIONAL H #include «cstdint> #include «iosfwd> #include «stdexcept> class Rational { intmax t num, den; public: enum sign type { POSITIVE, NEGATIVE }; Rational ( ) : num{0}, den{1} {} Rational ( intmax t numer ) : num{numer}, den{1} {} Rational ( intmax t numer, intmax t denom ) : num{numer}, den{denom} { normalize(); // reduces the Rational to lowest terms } inline intmax t num() const { return num; } inline intmax t den() const { return den; } // you'll implement all these in rational.cpp cpphomeworkhelp.com
  • 5. void normalize( ); float to float() const; double to double() const; sign type sign() const; Rational inverse() const; }; // An example multiplication operator inline Rational operator*( const Rational &a, const Rational &b ) { return Rational{ a.num() * b.num(), a.den() * b.den() }; } // Functions you'll be implementing: std::ostream& operator««( std::ostream& os, const Rational &ratio ); // ... and so on Notice the include guards at the top, protecting us from including the file multiple times. An expla nation of some of the constructs we use is in order. You’ll notice we use the intmax t type from the «cstdint> library. This type represents the maximum width integer type for our particular architecture (basically, we want to use the largest integers available). On my 64-bit computer, this means that we’lll cpphomeworkhelp.com
  • 6. f ind sizeof(Rational) to be 16 since it comprises two 64-bit (8-byte) integers. Look up an enum. We use this to define a type sign type in the scope of our class. Outside the class, we can refer to the type as Rational::sign type and its two values as Rational::POSITIVE and Rational::NEGATIVE. Contained in the header file is also a class that extends std::domain error to create a special type of exception for our Rational class. Look up the meaning of explicit; why do we use it in this particular constructor definition? Read through the code carefully and make sure you understand it. If you have any questions about the provided code or don’t know why something is structured the way it is, please ask about it on Piazza. This is the list of functions you should fill out. In the header file, you have a number of inline functions to complete, as shown here. #include <stdexcept> // ...near the bottom of the file class bad rational : public std::domain error { public: explicit bad rational() : std::domain error( "Bad rational: zero denom." ) {} }; cpphomeworkhelp.com
  • 7. inline Rational operator+( const Rational &a, const Rational &b ) {/* ... */} inline Rational operator-( const Rational &a, const Rational &b ) {/* ... */} inline Rational operatorI( const Rational &a, const Rational &b ) {/* ... */} inline bool operator«( const Rational &lhs, const Rational &rhs ) {/* ... */} inline bool operator==( const Rational &lhs, const Rational &rhs ) {/* ... */} There are also a number of functions declared in the header file which you should write an implemeatation for in the source file rational.cpp. Those declarations are: class Rational { // ...snipped public: // ...snipped void normalize(); float to float() const; double to double() const; sign type sign() const; }; std::ostream& operator««( std::ostream& os, const Rational &ratio ); cpphomeworkhelp.com
  • 8. Look in the existing rational.cpp file for extensive descriptions of the required functionality. In gcd.h, you can find the declaration for two functions which you may find useful: fast computation of the greatest common divisor and least common multiple of two integers. Feel free to include this header and use these functions in your code as needed. #ifndef 6S096 GCD H #define 6S096 GCD H #include «cstdint> intmax t gcd( intmax t a, intmax t b ); intmax t lcm( intmax t a, intmax t b ); #endif // 6S096 GCD H Input Format Not applicable; your library will be compiled into a testing suite, your implemented functions will be called by the program, and the behavior checked for correctness. For example, here is a potential test: cpphomeworkhelp.com
  • 9. #include "rational.h" #include «cassert> void test addition() { // Let's try adding 1/3 + 2/15 = 7/15. auto sum = Rational{ 1, 3 } + Rational{ 2, 15 } assert( sum.num() == 7 ); assert( sum.den() == 15 ); } You are strongly encouraged to write your own tests in test.cpp so that you can try out your imple mentation code before submitting it to the online grader. Output Format Not applicable. cpphomeworkhelp.com
  • 10. Code : Rational Number Library #ifndef _6S096_RATIONAL_H #define _6S096_RATIONAL_H #include <cstdint> #include <iosfwd> #include <stdexcept> class Rational { intmax_t _num, _den; public: enum sign_type { POSITIVE, NEGATIVE }; Rational() : _num{0}, _den{1} {} Rational( intmax_t numer ) : _num{numer}, _den{1} {} Rational( intmax_t numer, intmax_t denom ) : _num{numer}, _den{denom} { normalize(); } inline intmax_t num() const { return _num; } inline intmax_t den() const { return _den; } void normalize(); float to_float()const; cpphomeworkhelp.com
  • 11. double to_double()const; sign_type sign() const; Rational inverse() const; }; std::ostream& operator<<( std::ostream& os, const Rational &ratio ); inline bool operator==( const Rational &lhs, const Rational &rhs ) { return lhs.num() * rhs.den() == rhs.num() * lhs.den(); } inline bool operator<( const Rational &lhs, const Rational &rhs ) { if( lhs.sign() == Rational::POSITIVE && rhs.sign() == Rational::POSITIVE ) { return lhs.num() * rhs.den() < rhs.num() * lhs.den(); } else if( lhs.sign() == Rational::NEGATIVE && rhs.sign() == Rational::NEGATIVE ) { return lhs.num() * rhs.den() > rhs.num() * lhs.den(); } else { return lhs.sign() == Rational::NEGATIVE; } } inline Rational operator*( const Rational &a, const Rational &b ) { return Rational{ a.num() * b.num(), a.den() * b.den() }; } cpphomeworkhelp.com
  • 12. inline Rational operator+( const Rational &a, const Rational &b ) { return Rational{ a.num() * b.den() + b.num() * a.den(), a.den() * b.den() }; } inline Rational operator-( const Rational &a, const Rational &b ) { return Rational{ a.num() * b.den() - b.num() * a.den(), a.den() * b.den() }; } inline Rational operator/( const Rational &a, const Rational &b ) { return a * b.inverse(); } class bad_rational : public std::domain_error { public: explicit bad_rational() : std::domain_error("Bad rational: zero denominator" ) {} }; #endif // _6S096_RATIONAL_H Here is the source code file rational.cpp: #include "rational.h" #include "gcd.h" #include <stdexcept> #include <ostream> #include <iostream> #include <cmath> cpphomeworkhelp.com
  • 13. Rational Rational::inverse() const { return Rational{ _den, _num }; } Rational::sign_type Rational::sign()const { return _num >= 0 ? POSITIVE : NEGATIVE; } std::ostream& operator<<( std::ostream& os, const Rational &ratio ) { if( ratio == 0 ) { os << "0"; } else { if( ratio.sign() == Rational::NEGATIVE ) { os << "-"; } os << std::abs( ratio.num() ) << "/" << std::abs( ratio.den() ); } return os; } void Rational::normalize() { if( _den == 0 ) { throw bad_rational(); } if( _num == 0 ) { _den = 1; return; } cpphomeworkhelp.com
  • 14. auto g = gcd( std::abs( _num ), std::abs( _den ) ); _num /= g; _den /= g; if( _den < 0 ) { _num = -_num; _den = -_den; } } float Rational::to_float() const { return static_cast<float>( _num ) / static_cast<float>( _den ); } double Rational::to_double()const { return static_cast<double>( _num ) / static_cast<double>( _den ); } Below is the output using the test data: rational: 1: OK [0.007 seconds] OK! add 2: OK [0.006 seconds] OK! mult 3: OK [0.009 seconds] OK! add1024 4: OK [0.014 seconds] OK! add1024 cpphomeworkhelp.com
  • 15. 5: OK [0.158 seconds] OK! add32768 6: OK [0.007 seconds] OK! op<< 7: OK [0.289 seconds] OK! div65536 in 0.280000 s 8: OK [0.006 seconds] OK! phi, 0.000000e+00 9: OK [0.006 seconds] OK! (Bad rational: zero denominator) 10: OK [0.006 seconds] OK! xyz 11: OK [0.007 seconds] OK! pow2 12: OK [0.006 seconds] OK! X1z #ifndef _6S096_GCD_H #define _6S096_GCD_H #include <cstdint> intmax_t gcd( intmax_t a, intmax_t b ); intmax_t lcm( intmax_t a, intmax_t b ); #endif // _6S096_GCD_H #ifndef _6S096_RATIONAL_H #define _6S096_RATIONAL_H #include <cstdint> #include <iosfwd> #include <stdexcept> cpphomeworkhelp.com
  • 16. class Rational { intmax_t _num, _den; public: enum sign_type { POSITIVE, NEGATIVE }; Rational() : _num{0}, _den{1} {} Rational( intmax_t numer ) : _num{numer}, _den{1} {} Rational( intmax_t numer, intmax_t denom ) : _num{numer}, _den{denom} { normalize(); } inline intmax_t num() const { return _num; } inline intmax_t den() const { return _den; } // You should implement all of these functions in rational.cpp void normalize(); float to_float() const; double to_double() const; sign_type sign() const; const Rational inverse() const; }; std::ostream& operator<<( std::ostream &os, const Rational &ratio ); cpphomeworkhelp.com
  • 17. inline bool operator==( const Rational &lhs, const Rational &rhs ) { // You should implement } inline bool operator<( const Rational &lhs, const Rational &rhs ) { // You should implement } // This one is completed for you. We multiply two Rationals // by creating a new Rational as shown: // // a.num() b.num() a.num() * b.num() // ------- * ------- = ----------------- // a.den() b.den() a.den() * b.den() // // Our constructor should automatically reduce it to lowest terms, // e.g. 1/2 * 2/3 = 1/3 automatically. inline Rational operator*( const Rational &a, const Rational &b ) { return Rational{ a.num() * b.num(), a.den() * b.den() }; } inline Rational operator+( const Rational &a, const Rational &b ) { // You should implement } cpphomeworkhelp.com
  • 18. inline Rational operator-( const Rational &a, const Rational &b ) { // You should implement } inline Rational operator/( const Rational &a, const Rational &b ) { // You should implement } class bad_rational : public std::domain_error { public: explicit bad_rational() : std::domain_error( "Bad rational: zero denominator" ) {} }; #endif // _6S096_RATIONAL_H cpphomeworkhelp.com