Author Topic: Of Interest  (Read 924 times)

0 Members and 1 Guest are viewing this topic.

Nation of One

  • { }
  • { ∅, { ∅ } }
  • Posts: 4756
  • Life teaches me not to want it.
    • What Now?
Of Interest
« on: June 12, 2017, 12:40:12 pm »
Holden,

While searching for some examples of how one might go about writing a program in C++ to show the process of completing the square to put a quadratic equation in the form of a trinomial square, (x + p)^ 2 = q, not to mention the complications should I desire to print the solutions, if they even exist, in exact form (using radicals), I stumbled upon this video and wondered if you understood the language the man is speaking.  i am aware that there are around 40 different dialects in the large area called India.

The cool thing is that I find part of me understands what he is saying.  Well, not literally or verbatim, but I can follow his reasoning by looking at his code.



I still have this obsession with finding a way to force the computer to give results in exact form as opposed to decimal.   I see how SymPy does this at least in the IPython terminal, and I envy and appreciate the group of individuals who put that collection of modules together.

The reason why I enjoy building some things from scratch is because I like to come face to face with the complications of how one would go about programming a computer to do such things.

It really makes one appreciate what we can do with pencil and paper, drawing those symbols like the radical sign.

I would like to be able to write a program that gives output like SymPy:

In [1]: solve(x**2 + 5*x - 5,x)
Out[1]:
⎡  5      3⋅√5            3⋅√5   5  ⎤
⎢- ─  + ────,      - ──── - ─ ⎥
⎣  2        2                  2     2  ⎦

but also I would like to display each step.

I am thinking along the lines of combining with Rational class put together for dealing with fractions, and then incorporating some of the following techniques for keeping the radicals in exact form.

The following is some code I "put together" which I run at the command line, such as sqrt 180.

I can always incorporate the the parts minus the "show and tel"l parts into another program.  The code below is not the same as the attached file.   

I leave it here as an example of the kind of goofy things I become engrossed in when tinkering around with mathematics and programming.  Incorporating some programming can breathe life into elementary algebra.   It's a process of rediscovery.   The two disciplines really do complement each other.

_______________________________________________________________________________________

#include<iostream>
#include <cstdlib>
#include<cmath>

#define EPSILON 0.0000001 // least minimum value for comparison

double SquareRoot(double _val);
void SquareRoot(int _integer);

int main(int argc, char* argv[])
{
  if (argc !=2)  {
    std::cout << "USE: " << argv[0] << " <positive integer>\n";
    std::cout << "to simplify square root of integer.\n";
    return 1;
  }

   int N = atoi(argv[1]);
  if ( (N <= 0)  ||  (N > 9999) )   {
    std::cout << "Input positive integer, goddamnit!\n";
    std::cout << "And make it less than 10000, please.\n";
    return 2;
  }
int factor = 316; // 31^2 = 961; 316^2 = 99856
while ( N%(factor*factor) != 0 )  {
  factor -= 1;
}
int r = N/(factor*factor);
std::cout << "\nSimplified square root of " << N << " is ";
if (factor > 1) std::cout << factor << "*";
std::cout << "sqrt(" << r << ")\n";
std::cout << std::endl;
std::cout << "Trial Square Root of " << N << ":\n";
SquareRoot(N);
std::cout << std::endl << std::endl;
double n = atof(argv[1]);
double sqroot = SquareRoot(n);
std::cout << "Using SquareRoot(" << n << ") = " << sqroot;
double s = sqrt(n);
std::cout << "\nUsing sqrt(" << n << ") = " << s << std::endl;
return 0;

}

double SquareRoot(double _val) {
    double low = 0;
    double high = _val;
    double mid = 0;

    while (high - low > EPSILON) {
            mid = low + (high - low) / 2; // finding mid value
            if (mid*mid > _val) {
                high = mid;
            } else {
                low = mid;
            }
    }
    return mid;
}

void SquareRoot(int _integer)  {
   int sqr = 1;
   while (sqr*sqr < _integer)  {
     sqr += 1;
   }
   int b = sqr;
   int a = sqr - 1;
   std::cout << a*a << " < " << _integer << " < " << b*b;
   std::cout << "\nSo we know that sqrt("<< a*a << ") < sqrt(" << _integer;
   std::cout << ") << sqrt(" << b*b << ")\n";
   std::cout << "That is, " << a << " < sqrt(" << _integer;
   std::cout << ") < "  << b << std::endl;

   int i;
   double c, d;
   double digit = 1;
   double nths = double(a) + 0.1*digit;

   for (int i=0; i < 4; i++)  {
     std::cout << "\nSimilarly, \n";
     while (nths*nths < _integer) {
       nths += 0.1*digit;
     }
     d = nths;    // store value greater than square root
     c = nths - 0.1*digit;  // store value less than square root
     std::cout << "\nSince (" << c << ")^2 = " << c*c;
     std::cout << " and since (" << d << ")^2 = " << d*d << ",\n";
     std::cout << "we know that " << c << " < sqrt(" << _integer;
     std::cout << ") < " << d << std::endl;
     digit = 0.1*digit;
     nths = c + 0.1*digit;

   }

}

_________________________________________________
To whom it may concern:  The attached file was uploaded as txt, since those are the rules for freeboards.

Just rename as cts.cpp and compile (with g++ or whatever):

g++ -g cts.cpp -std=c++11 -o cts
--- needs -std=c++11 for std::to_String()

./cts

It is an attempt to show results in exact "human form" along with decimal results.

[The file has been attached to a post below (in this thread)]
« Last Edit: March 03, 2019, 12:04:44 pm by Miserable Mike »
Things They Will Never Tell YouArthur Schopenhauer has been the most radical and defiant of all troublemakers.

Gorticide @ Nothing that is so, is so DOT edu

~ Tabak und Kaffee Süchtigen ~

Share on Facebook Share on Twitter


Holden

  • { ∅, { ∅ } }
  • Posts: 5070
  • Hentrichian Philosophical Pessimist
Re: Of Interest
« Reply #1 on: June 13, 2017, 09:49:46 am »
I have downloaded the attachment.
(The bird of a year old has no idea of the eggs for which it builds a nest; the young spider has no idea of the prey for which it spins a web; nor has the ant-lion any idea of the ant (his prey) for which he digs a pit for the first time.

In the timber in which it is to await metamorphosis, the larva of the stag beetle makes the hole twice as big if it is going to be a male beetle as it does if it is going to be a female, so that if it is a male there may be room for the horns, of which, however, it still has no inkling...)


I played the video,the narrator is speaking one of the South Indian languages, I think,it is either Tamil or Telugu.
I am,however,a Northerner,here they mostly speak Hindi.
I cannot make out what he is saying,except that he is speaking one of the south Indian languages.
La Tristesse Durera Toujours                                  (The Sadness Lasts Forever ...)
-van Gogh.

Nation of One

  • { }
  • { ∅, { ∅ } }
  • Posts: 4756
  • Life teaches me not to want it.
    • What Now?
Re: Of Interest
« Reply #2 on: June 13, 2017, 11:48:34 am »
Thanks Holden of Northern India. 

I added a few lines of code and upload to the above as cts.txt so as to distuinguish from the first one you downloaded.  It is not significantly different, but simply tweaks some of the output (dividing by greatest common divisor of numerator and denominator) to make it more in line with how we would do this by hand.

While I did not understand the man's actual words, his explanation of how to use the template class was crystal clear.   Basically he shows that, by using template<class T>, he could pass the function either integers or decimals without having to write two separate functions.
____________________________________________________________________
update:   13 June 2017 15:05

While running the program for 5*x^2 + x - 3 = 0 (input 5 1 -3), where the result is { (-1 + sqrt(61))/10, (-1 - sqrt(61))/10 }, there was a core dump because I had not accounted for a situation when there was no factor outside the radicand when searching the string for "*".

It was fun tracking this down with gdb debugger.

I added the following at around lines 96-102:

 if (str.find("*") == std::string::npos)  // No factor outside radicand
   {
     w = 1;
   }
   else {
     w = std::stoi( str.substr(0, str.find("*")) );
   }

_______________________________________________________________
The attached file cts.txt (cts.cpp) contains the fix.
______________________________________________

Footnote:  This fix worked when compiling under Gentoo Linux, Arch Linux, and Windows 10, but in Ubuntu, when it comes across the sqrt() without finding *, it still aborts with
terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi


It's not really an issue since the results are displayed correctly at that point (just before output of decimal representation).  I even tried:

std::string::size_type idx;
idx = str.find("*");
   if (idx == std::string::npos )  // No factor outside radicand
   {
     w = 1;
   }
   else {
     w = std::stoi( str.substr(0, str.find("*")) );
   }


I ran through the debugger and this is handled perfectly.  It doesn't find "*" and assigns the value of 1 to w.  I only extract that info because i want to reduce to lowest terms, which I do.

The weird thing is that it works fine under other the operating systems mentioned.

So, I'm not going crazy with fixes.  It works, and I learned a thing or two in the process.  Remember, I only wrote this code to see how to go about displaying results in exact (human) form (with radicals) before decimal approximations are displayed.

PEACE!
« Last Edit: March 03, 2019, 12:03:56 pm by Miserable Mike »
Things They Will Never Tell YouArthur Schopenhauer has been the most radical and defiant of all troublemakers.

Gorticide @ Nothing that is so, is so DOT edu

~ Tabak und Kaffee Süchtigen ~

Nation of One

  • { }
  • { ∅, { ∅ } }
  • Posts: 4756
  • Life teaches me not to want it.
    • What Now?
Re: Of Interest
« Reply #3 on: March 03, 2019, 12:02:08 pm »
I changed the above text file to .cpp file as we are able to do so now.

There is no rush to look at the code or to even compile the program, nor any request from me that anyone look into the method of completing the square.

I merely place it here for posterity.  One day it may be of interest to someone.  The code may appear to have too much unnecessary output, but the entire point of this code is to expalin the process to someone who is learning to complete the square by hand with pencil and paper.   Much of my code takes on the extra burden of explaining itself in real time.
________________________________________________________________________________________________________________

// g++ -g completesquare2.cpp -std=c++11 -o cts
// Need -std=c++11 for std::to_String()

#include<iostream>
#include<cstdlib>
#include<cmath> // for sqrt() function
#include<string>

std::string simplifyRadical(int radicand);

template<class T>
int completeSquare(T a, T b, T c);

int gcd(int a, int b);

int main() {
  double a,b,c;
  std::cout << "a*x^2 + b*x + c = 0\n\n";
  std::cout << "Enter a, b, c (a>0) :\n";
  std::cin >> a >> b >> c;
  completeSquare(a,b,c);

//std::cout << "\nTesting simplifyRadical(144) : " << simplifyRadical(144) << std::endl;
//std::cout << "\nTesting simplifyRadical(160) : " << simplifyRadical(160) << std::endl;
  return 0;
}

template<class T>
int completeSquare(T a, T b, T c)
{

  double d = (b*b) - (4*a*c);
  std::cout << "\nQuadratic Equation:  (" << a << ")*x^2 + ("
                 << b << ")*x + (" << c << ") = 0\n\n";

if (a > 1)  {
    std::cout << "Divide through by " << a;
    std::cout <<  "\nx^2 + (" << b << "/" << a << ")*x + (" << c << "/" << a << ") = 0";
    std::cout <<  "\nx^2 + (" << b << "/" << a << ")*x =  (" << -c << "/" << a << ")\n";
}
  std::cout << "-----------------------------------------------------------\n";
  std::cout << "Complete the square : \n";
  std::cout << "\nx^2 + (" << b << "/" << a << ")*x + (" << b << "/" << 2*a
                 << ")^2  =  (" << -c << "/" << a << ") + (" << b << "/" << 2*a
                                << ")^2\n";
  std::cout << " [ x + (" << b << "/" << (2*a) << ") ]^2 =  (" << -c << "/" << a << ") + (" << b*b
                << "/" << 4*a*a << ")\n";
std::cout << " [ x + (" << b << "/" << (2*a) << ") ]^2 =  (" << d << "/" << (4*a*a) << ")\n";
std::cout << "-----------------------------------------------------------\n";

if (d < 0)
{
  std::cout << "\nSince the square of a real number must be a nonnegative real number,\n ";
  std::cout << "the equation, (" << a << ")*x^2 + (" << b << ")*x + (" << c << ") = 0 \n";
  std::cout << "has no real-number solution.\n";
  std::cout << "\nRoots are Complex (not real-numbers) : ";
  double r = sqrt(-d);
  double r1 = -double(b)/(2*a);
  double r2 = r/(2*a);
  std::cout << "\nReal Part : " << r1;
  std::cout << "\nImaginary Part : " << r2;
  std::cout << "\n\nThus, extending the replacement set of the variable to include\n ";
  std::cout << "imaginary numbers, we can write the COMPLEX solution set as :\n\n";
  std::cout << "{ " << r1 << " + " << r2 << "i, " << r1 << " - " << r2 << "i }\n";

  // Test out simplifyRadical with Complex results (just for the hell of it)
  std::cout << "\nAn attempt to represent EXACT COMPLEX SOLUTIONS:\n";
  std::string str = simplifyRadical(-d);
  std::cout << " \nx = [" << -b << " + " << str << " i ] / " << 2*a;
  std::cout << " \nx = [" << -b << " -  " << str << " i ] / " << 2*a;

  std::cout << "\n\nReal Part : " << -b << '/' << 2*a;
  std::cout << "\nImaginary Part : " << "[+/-] " << str << '/' << 2*a;

   if (str.find("*") != std::string::npos)  {
     int w = std::stoi( str.substr(0, str.find("*")) );
     //std::cout << "\nw from string is " << w << "\n\n";
     int g = abs( gcd(2*a, gcd(b, w)) );
     std::cout << "\n\ngcd(" << 2*a << ", gcd(" << b << ", " << w << ")) = " << g << "\n\n";
     std::cout << "\n-----------------------------------------------------------\n";

     // Divide through by greatest common divisor
     std::cout << "Reducing to lowest terms : \n";
     if (2*a/g != 1)  {
          std::cout << " \nx = [" << -b/g << " + " << simplifyRadical(-d/(g*g))  << " i ] / " << (2*a)/g;
          std::cout << " \nx = [" << -b/g << " -  " << simplifyRadical(-d/(g*g)) << " i ] / " <<(2*a)/g;
     }
     else {
        std::cout << " \nx = " << -b/g << " + " << simplifyRadical(-d/(g*g))  << " i";
        std::cout << " \nx = " << -b/g << " -  " << simplifyRadical(-d/(g*g)) << " i";
     }
     std::cout << std::endl;
   }
   else {
     int g = abs( gcd(2*a, b));
     std::cout << "\n\ngcd(" << 2*a << ", " << b << ") = " << g << "\n\n";
     std::cout << "\n-----------------------------------------------------------\n";

     // Divide through by greatest common divisor
     std::cout << "Reducing to lowest terms : \n";
     if (2*a/g != 1)  {
          std::cout << " \nx = [" << -b/g << " + " << simplifyRadical(-d/(g*g))  << " i ] / " << (2*a)/g;
          std::cout << " \nx = [" << -b/g << " -  " << simplifyRadical(-d/(g*g)) << " i ] / " <<(2*a)/g;
     }
     else {
        std::cout << " \nx = " << -b/g << " + " << simplifyRadical(-d/(g*g))  << " i";
        std::cout << " \nx = " << -b/g << " -  " << simplifyRadical(-d/(g*g)) << " i";
     }

     std::cout << std::endl;
   }
   std::cout << std::endl << std::endl;

}
else if (d == 0) {
  std::cout << "\nThere is only one root, called a double root: " << -b/(2*a);
  std::cout << std::endl;
}
else if (d > 0)  {
  std::cout << " x + (" << b << "/" << (2*a) << ")  =  +- sqrt(" << d << "/" << (4*a*a) << ")\n";
  std::cout << "\n\nThere are two different real roots of the equation,  \n("
                << a << ")*x^2 + (" << b << ")*x + (" << c << ") = 0 \n\n";
  std::cout << " x = (" << -b << "/" << (2*a) << ") +/- sqrt(" << d << "/" << (4*a*a) << ")\n";
  std::cout << " x = (" << -b << "/" << (2*a) << ") +/- [sqrt(" << d << ") / " << 2*a << "]";
  std::cout << " \nx = [" << -b << " +/- sqrt(" << d << ") ]  / " << 2*a;

  std::string str = simplifyRadical(d);
  std::cout << " \n\nx = [" << -b << " + " << str << "] / " << 2*a;
  std::cout << " \nx = [" << -b << " -  " << str << "] / " << 2*a;

 if (str.find("*") != std::string::npos)  {
   int w = std::stoi( str.substr(0, str.find("*")) );
  // std::cout << "\nw from string is " << w << "\n\n";
   int g = abs( gcd(2*a, gcd(b, w)) );
  std::cout << "\n\ngcd(" << 2*a << ", gcd(" << b << ", " << w << ")) = " << g << "\n\n";
  std::cout << "\n-----------------------------------------------------------\n";

   // Divide through by greatest common divisor
   std::cout << "Reducing to lowest terms : \n";
   std::cout << " \nx = [" << -b/g << " + " << simplifyRadical(d/(g*g))  << "] / " << (2*a)/g;
   std::cout << " \nx = [" << -b/g << " -  " << simplifyRadical(d/(g*g)) << "] / " <<(2*a)/g;
 }
 else {
  int g = abs( gcd(2*a, b) );
  std::cout << "\n\ngcd(" << 2*a << ", " << b << ") = " << g << "\n\n";
  std::cout << "\n-----------------------------------------------------------\n";

   // Divide through by greatest common divisor
   std::cout << "Reducing to lowest terms : \n";
   if (2*a/g != 1)  {
      std::cout << " \nx = [" << -b/g << " + " << simplifyRadical(d/(g*g))  << "] / " << (2*a)/g;
      std::cout << " \nx = [" << -b/g << " -  " << simplifyRadical(d/(g*g)) << "] / " <<(2*a)/g;
   }
   else {
      std::cout << " \nx = " << -b/g << " + " << simplifyRadical(d/(g*g));
      std::cout << " \nx = " << -b/g << " -  " << simplifyRadical(d/(g*g));
   }
 }
  std::cout << "\n\nThe decimal representation of the two solutions are :\n";
  std::cout << "Root 1:  x = " << -b/(2*a)  + sqrt(d /(4*a*a)) << "\n";
  std::cout << "Root 2:  x = " << -b/(2*a)  - sqrt(d /(4*a*a)) << "\n";


}

/*  std::cout << "\n\nPess <ENTER> to exit.\n";
  std::cin.ignore().get();  // Pause Command for Linux Terminal
  */
  return 0;
}

// Reducing radicals to simplest terms for posterity
std::string simplifyRadical(int radicand)  {

  int factor = 316; // 31^2 = 961; 316^2 = 99856
  while ( radicand%(factor*factor) != 0 )  {
    factor -= 1;
  }
  int r = radicand/(factor*factor);
  std::string reduced = "";

  if ( (factor > 1) && (r != 1) )  {
    reduced.append(std::to_string(factor) + "*");
//    reduced.append("*");
  }
  if (r == 1)  {  reduced.append(std::to_string(factor));  }
  else {
      reduced.append("sqrt(" + std::to_string(r) + ")");
  }
  return reduced;
}

int gcd(int a, int b)    {
  int t;
  while (a)
    {
      t = a;
      a = b%a;
      b = t;
    }
  return b;
}
« Last Edit: March 03, 2019, 12:33:53 pm by Miserable Mike »
Things They Will Never Tell YouArthur Schopenhauer has been the most radical and defiant of all troublemakers.

Gorticide @ Nothing that is so, is so DOT edu

~ Tabak und Kaffee Süchtigen ~

Nation of One

  • { }
  • { ∅, { ∅ } }
  • Posts: 4756
  • Life teaches me not to want it.
    • What Now?
Re: Of Interest
« Reply #4 on: August 23, 2019, 10:20:27 am »
For now, I am going to slowly add some source code to "classical" algebraic computations, starting with the Completing the Square code that transformed into template (generic programming), at gitHub:

https://github.com/Gorticide/Algebra_Revisited

Eventually, much more will be added, the gods be willin' and the cricks don't rise.

Don't let the mother fuuckers grind you down!

Now, what this means is, one might go to github, locate RAW page for completesquare2.cpp,

https://raw.githubusercontent.com/Gorticide/Algebra_Revisited/master/completesquare2.cpp

select all, copy, and paste in http://cpp.sh/

Then run.

(Of course, paste over the sample code in C++ Shell editor)

There are a great many things I have been documenting in pen and pencil, and may get around to posting such Guides here as well since I have returned here for technical guidance repeatedly.

Now, the mother is talking endless chatter at me.  My brain will surely be hijacked today at some point.  Absurd joke, this misery machine ... endless doctor visits (and stupid smart phones  ::) )

 >:(
« Last Edit: August 23, 2019, 10:30:25 am by gorticide »
Things They Will Never Tell YouArthur Schopenhauer has been the most radical and defiant of all troublemakers.

Gorticide @ Nothing that is so, is so DOT edu

~ Tabak und Kaffee Süchtigen ~

Holden

  • { ∅, { ∅ } }
  • Posts: 5070
  • Hentrichian Philosophical Pessimist
Re: Of Interest
« Reply #5 on: August 24, 2019, 10:10:54 am »
Don't let the mother fuuckers grind you down!-Herr Kaspar
I will try but I don't feel well at all.Its really bad -like I don't even breathe properly due to anxiety.My panic attacks are really terrible.

Take care.
La Tristesse Durera Toujours                                  (The Sadness Lasts Forever ...)
-van Gogh.

Nation of One

  • { }
  • { ∅, { ∅ } }
  • Posts: 4756
  • Life teaches me not to want it.
    • What Now?
Re: Of Interest
« Reply #6 on: August 26, 2019, 12:31:31 pm »
Something within me has changed.  I also feel a constant anxiety, and I have come to the conclusion that this is simply what it feels like to be [Will-to-Live].  It's ugly and unpleasant.  Those of us who like to think of ourselves as "good-natured" might become upset when we see ourselves as we truly are:  vulnerable, isolated animal life, hungry-all-the-time.

I have reached a point where I am reluctant to speak frankly with others.

There are too many obsticles to genuine communication, and when I am most honest, people will jokingly remind me that I am "certifiably crazy."    I sometimes suspect that the most well-adapted citizens take a certain pleasure in witnessing a fairly intelligent and well-educated man at a total loss as far as "making it" in this world.

Fortunately I am living in the United States, where nearly half the population is living on governement relief, many for "mood disorders" and other "personality traits" which make the daily abuse suffered by most employees unacceptable.  That is, I am not servile enough.  it has nothing to do with "sanity" vs "insanity."

I have been diagnosed with a mental disorder because my mind is a little more FREE than my more obedient, ass-licking and ambitious "sisters and brothers."

 :-\
Things They Will Never Tell YouArthur Schopenhauer has been the most radical and defiant of all troublemakers.

Gorticide @ Nothing that is so, is so DOT edu

~ Tabak und Kaffee Süchtigen ~

Nation of One

  • { }
  • { ∅, { ∅ } }
  • Posts: 4756
  • Life teaches me not to want it.
    • What Now?
Re: Of Interest
« Reply #7 on: March 30, 2020, 12:50:45 pm »
You can finally run that "Completing the Square" program.

Enter a b c for any quadratic equation ax^2 + bx + c = 0 : coding bum teaching beyond the grave ... while nurses with arrogant breasts and protruding a$$es wrestle to make sense of the hatred burning in their hearts for those heartless meat puppets whose strings resist strongly being recruited by the social apparatus.  I have been told by the TV that the best thing I can do for the world is stay home.  That's what I've been doing.     I've been on ECONOMIC HOUSE ARREST for decades, living from hand to mouth, as they say.

I suppose the hen-house will be cursing those reluctant to volunteer for the front lines.

Maybe were I younger and less cynical. less shot-out, less responsible for assisting my mother through her most insane days yet.

The fixed code is at github in Repository ALGEBRA REVISITED.

Many of the other programs I wished to share with you from ]github will not compile at C++ Shell since they require multiple files, such as fraction.cpp to be included on the command line.   This one is a good start. as far as actually helping user to better understand the "Completing the Square" algorithm/process/recipe.

Other code I have uploaded may have been more elegant, whereas this was brute force done awhile back.

Still, it shows some ingenuity.
Things They Will Never Tell YouArthur Schopenhauer has been the most radical and defiant of all troublemakers.

Gorticide @ Nothing that is so, is so DOT edu

~ Tabak und Kaffee Süchtigen ~