c++ - Fraction class for finding square root 2 convegerence -


i made class can add, multiply , divide fractions presented below

class fraction {     unsigned long long num, denom;  public:     fraction(int n, int d): num{n}, denom{d} {};     fraction& operator+=(fraction frac);     fraction& operator*=(fraction frac);     fraction& operator/=(fraction frac);     friend ostream& operator<<(ostream& os, const fraction& frac); };  fraction& fraction::operator+=(fraction frac)  {     unsigned long long least_mult = lcm(denom, frac.denom); // least-common multiple     num *= least_mult/denom;     num += frac.num*least_mult/frac.denom,     denom = least_mult;     return *this; }  fraction& fraction::operator*=(fraction frac) {     num *= frac.num;     denom *= frac.denom;     return *this; }  fraction& fraction::operator/=(fraction frac) {     num *= frac.denom;     denom *= frac.num;     return *this; }  ostream& operator<<(ostream& os, const fraction& frac) {     os << frac.num << '/' << frac.denom;     return os; }  fraction operator+(fraction a, fraction b) {return a+=b;} fraction operator*(fraction a, fraction b) {return a*=b;} fraction operator/(fraction a, fraction b) {return a/=b;  } 

when try compute square root 2 convergence using sqrt_two = 1 + 1/(1+sqrt_two) recursive relation when 4478554083/3166815962, next value 8399386631/7645270045 totally off 1.098, , therefore subsequent values wrong too.

int main()  {     fraction one(1, 1), sqrt_two(3,2);      for(int = 1; < 50; ++i)     {         sqrt_two = 1 + one/(one+sqrt_two);         cout << sqrt_two << endl;     }      return 0; } 

i have tried 1+1/(1+8399386631/7645270045)) manually on calculator , result still square root convergent.

looking @ code, there lines susceptible overflow. perhaps 1 has happened in case. example,

num += frac.num*least_mult/frac.denom, 

(which looks contains typo, incidentally).

so, i'd suggest see how check overflow, , somehow incorporate class. i'm not sure should in such case, though.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -