Find root without while and for loop - c++

The program I'm coding should find the root of a given double.
The condition is: you're not allowed to use while and for loops. any kind of loops are not allowed.
Our professor said it's forbidden to use the stdlib function sqrt().
I started to code but it's still not working. hope anyone can help.
#include <cstdlib>
#include <iostream>
using namespace std;
double mysqrt(double a, double b, double c);
int main(int argc, char** argv) {
double dBegin{0};
double dOldroot{0};
double dNewroot{0};
double a{0};1
cin >> dBegin;
dOldroot = dBegin;
mysqrt(a, dOldroot, dNewroot);
cout << dNewroot;
return 0;
}
double mysqrt(double a, double b, double c) {
c = (b + (a / b)) / 2.0;
if (a != 8) {
c = mysqrt(a++, b, c);
}
return c;
}

I'm using Newton-Raphson's Method to find out the square-root of a given number num (in my code).
You may find this video link useful: Click Here. Using this algorithm i've solved this problem.
Here is my code.
#include <iostream>
using namespace std;
/* we are gonna use Newton-Raphson's method to find its square because
it converges quickly, even calculators use this algo. to find the sqr-root */
double find_sqrt(double x, int num, int count) {
if(count == 0)
return x;
double f_x = x*x - num;
double f_dx = 2*x;
double res = x - (f_x/f_dx);
x = find_sqrt(res, num, count -1);
return x;
}
int main() {
double num;
cin >> num;
/* Here 20 is the maximum number of times it will run and
num/2 is the random number send to the function between the range 1 to num */
cout << find_sqrt(num/2, num, 20);
return 0;
}
The result might not be much precise but it will always be almost near to the actual square-root of the number.
Reason: Floating-precision error. You must be knowing about this i believe.

You have junk 1 to cause compile error after double a{0};
Your code will do infinite recursion because the first argument won't updated. Using double for counter isn't also a good idea.
You are throwing away the value returned from mysqrt in main().
Using arguments as local variables without reading its value isn't a good idea.
Fixing these errors, your code will be like this:
#include <cstdlib>
#include <iostream>
using namespace std;
double mysqrt(int a, double b);
int main(int argc, char** argv) {
double dBegin{0};
double dOldroot{0};
double dNewroot{0};
int a{0};
cin >> dBegin;
dOldroot = dBegin;
dNewroot = mysqrt(a, dOldroot);
cout << dNewroot;
return 0;
}
double mysqrt(int a, double b) {
double c = (b + (a / b)) / 2.0;
if (a != 8) {
c = mysqrt(a + 1, b);
}
return c;
}
This code failed to calculate square root, but compiled and exited soon when ran.

Related

What should I do so that "nan" doesn't show up in console?

My teacher gave this homework. Basically I have two numbers, a and b. I have to show to console answer of this formula for every 'a' number added h=(b-a)/10 but in console I see just nan. How can I solve this error?
My code is:
#include <iostream>
#include <math.h>
using namespace std;
double s(double x){
long f = 1;
long double anw=1;
for(int k=1;k<=100;k++){
f=k*f;
anw=((pow((x-1),k)*pow(log(3),k))/f)+anw;
}
return anw;
}
int main(){
double a=0.2, b=0.8, h;
h=(b-a)/10;
for(double x=a; x<=b ;x+=h){
cout<<"s(x)="<<s(x)<<endl;
}
return 0;
}
Sorry for my bad English!
You get a signed integer overflow in f=k*f; so I suggest that you make f a double:
double s(double x){
double f = 1; // double
long double anw=1;
for(int k=1;k<=100;k++){
f = k * f; // or else you get a signed integer overflow here
// f *= k; // a simpler way of writing the above
anw=((pow((x-1),k)*pow(log(3),k))/f)+anw;
}
return anw;
}
Another note: Include the C++ header cmath instead of the C header math.h.

How to find square root with 20 digit precision in C++?

Hi guys I'm stuck with this homework where I need to find the root of equation using Bisection method with precision 10^-20 aka 0.00000000000000000001 so at first I though it was cause I wasn't using long double and also L at the end of the numbers, however even when I use it my last 3 digits are not correct, for the code that is given below ask you to give the number for a in my case is 5 , so I get 2.3227751229355622087
while the correct answer should be 2.3227751229355622988, I really can't find my mistake , will be happy if some1 assist me with this problem.
For your reference, here's a description and illustration of the Bisection method.
Here's my code:
#include<iostream>
#include<cmath>
#include<math.h>
#include<iomanip>
using namespace std;
long double f(long double x, long double a);
long double F = 123456L % 100L;
long double f(long double x, long double a)
{
long double sum = pow(x, 5) - a*x - F;
return sum;
}
int main()
{
cout.setf(ios::fixed);
long double a, b, c, fa, fb, fc;
long double e;
long double aa;
bool flag = true;
while (cin >> aa)
{
cout.precision(19);
flag = true;
a = 0L;
b = 10L;
e = 0.00000000000000000001L;
if (f(a, aa)*f(b, aa)>0)
{
flag = false;
}
while(fabs(a-b)>=e){
c = (a + b) / 2.0L;
fa = f(a, aa);
fb = f(b, aa);
fc = f(c, aa);
if (fc == 0)
{
break;
}
if (fa*fc>0)
{
a = c;
}
else if (fa*fc<0)
{
b = c;
}
}
if (flag == true)
{
cout << c << endl;
}
else
{
cout << "NO SOLUTION" << endl;
}
}
return 0;
}
The problem was that I was using the wrong compiler (Visual Studio).
As soon as installed another compiler, there wasn't any problem with the 20 digit precision. As I investigated more, it appears that some compilers have a limit after the decimal to 14 or 15.
If c++ refuses to round your number to higher precision change the compiler :)

Keep getting 1.#INF as my output

#include <iostream>
using namespace std;
double calc(int a, int b);
int main()
{
int n1, n2;
cout << "Enter a number for a: ";
cin >> n1;
cout << "Enter a number for b: ";
cin >> n2;
cout << calc(n1, n2) << endl;
system("PAUSE");
return 0;
}
double calc(int a, int b)
{
double s;
s = (a) / ((sqrt(a / b)));
return s;
}
This program is meant to check whether the two integers are greater than zero. If it is it will calcualte the formula. Otherwise if one of the integers is zero or less than zero it will not return anything and exit the program.
My question here is that no matter what I input for a and b, i keep getting 1.#INF as the output and I have no idea why. I've checked the formula in a seperate program and it worked fine.
Any ideas?
Here, you are operating with int numbers:
s = (a) / ((sqrt(a / b)));
If a is less then b, then a/b (both are integers, remember, so the fractional part of the result will simply be lost) will be equal to 0, which leads to division by 0. You need to cast one of the numbers to double:
s = (a) / ((sqrt(static_cast<double>(a) / b)));
sqrt takes and returns a double. When you call it with integer arguments it will be converted in a double, and will thus get the value of infinity.
change your function signature to:
double calc(double a, double b);
and declare n1 and n2 as double.
You say that the function will exit the program when one of the integers are 0 or less, but where?
Try to check them like this:
Additionally, you should have a check whether a is greater than b
double calc(int a, int b)
{
double s;
if(a <= 0) exit(-1);
if(b <= 0) exit(-1);
if(a < b) exit(-1);
s = (a) / ((sqrt(a / b)));
return s;
}
You are having problems with infinity. For it use isinf. Here is some sample usage:
#include <stdio.h> /* printf */
#include <math.h> /* isinf, sqrt */
int main()
{
printf ("isinf(-1.0/0.0) : %d\n",isinf(-1.0/0.0));
printf ("isinf(sqrt(-1.0)): %d\n",isinf(sqrt(-1.0)));
return 0;
}
output:
isinf(-1.0/0.0) : 1 isinf(sqrt(-1.0): 0

square root of a number with recursion

#include<iostream>
#include<cmath>
using namespace std;
int e=0.001;
double yk(int k,double x){
if(k==0) return 1;
return 0.5*(yk(k-1,x) + x/yk(k-1,x));
}
double square(double x,int k)
{
if(fabs(yk(k,x)*yk(k,x) - x)<e) return yk;
return square(x,k+1);
}
int main()
{
cout<<yk(5,2);
return 0;
}
I need to calculate the square root of a number with Newton's formula which calculates y[k] till fabs(y[k] * y[k] -x)>e (a small number like 0.0001);
So if sqrt (2)= 1.41421356237 and e=0.0001 my function must back 1.4142 .
..This is the program I wrote.. I know that it is buggy, so i will be very thankful if sb help me :)))
The variable e should be float or double.
The error you get is not because of the fabs function, it is because you are trying to return a pointer to the yk function, but square returns a double
#include <iostream>
#include <cmath>
using namespace std;
double e=0.001;
double yk(int k,double x){
if(k==0) return 1;
return 0.5*(yk(k-1,x) + x/yk(k-1,x));
}
double square(double x,int k)
{
double res = yk(k, x);
if (fabs(res*res - x) < e) return res;
return square(x,k+1);
}
int main()
{
cout << yk(5,2); // Actually you don't call square....
// it works even if you do square(2, 5), this way you get the root of two
// doing at least 5 iterations, and if it is not enough (error > e) the
// computer goes on until it gets an error < e
return 0;
}

Program crashes when inputs are high values

My code works when the values are small e.g. [a = 1, gos = 0.5, N = 1] & [a = 1, gos = 0.2 , N = 2].
However, it crashes when bigger values are entered. e.g.[a = 10, gos = 0.01, N = 18] & [a=50, gos=0.01, N=64].
How can I fix it?
Here's the code:
#include <cstdlib>
#include <iostream>
using namespace std;
double num_trunks(double A, double B, int N);
double num_trunk_checker(double B, double gos, int N, double A);
double num_trunks(double A, double B, int N)
{
double gos_prev = 1;
double gos;
int k = 1;
while (k != (N+1))
{
gos = (A*gos_prev)/(k+(gos_prev)*A);
gos_prev = gos;
k++;
};
num_trunk_checker(B,gos,N,A);
}
double num_trunk_checker(double B, double gos, int N, double A)
{
if (B != gos)
{
N = N + 1;
num_trunks(A,B,N);
}
else
{
cout << "Number of trunks: " << N << "\n";
}
}
int main(int argc, char *argv[])
{
double A, gos;
int N = 1;
cout << "A: ";
cin >> A;
cout << "gos: ";
cin >> gos;
num_trunks(A,gos,N);
system("PAUSE");
return EXIT_SUCCESS;
}
In num_trunks(A, B, N), you calculate a gos value, and then call num_trunk_checker(B, gos, N, A). But in num_trunk_checker, if B does not match gos, you turn around and call num_trunks(A, B, N+1). So the only thing that changed is a larger N, and you get infinite recursion if gos never equals B.
num_trunks(A, B, N)
calculuate gos (which has to be less than 1)
num_trunk_checker(B, gos, N, A)
num_trunk_checker(B, gos, N, A)
if (B != gos) num_trunks(A, B, N+1)
It is possible for gos to step over the value of B, so you never get equality.
Perhaps what you meant was:
if (gos > B) //...
you should read the FAQ about floating point comparisons
http://www.parashift.com/c++-faq/floating-point-arith.html
then try sth like
if (fabs(B-gos)<1.e-6)
in num_trunk_checker function
Without more information (what crashes? How long does it take?) it is impossible to solve your problem perfectly. But some reasonable guesses can be made.
Floating point comparisons are not completely accurate and are usually done by subtracting the two values and comparing against a small value (called epsilon). It might be better, when checking (B != gos), to do something like (B - gos < .00001). Without this, the computation may not terminate; and if it did not, the recursion would continue indefinitely, until the stack overflowed and the program crashed.
Another possibility (I am not running the program to see what happens myself) is that with larger values, the multiplication causes them to overflow (to exceed the maximum possible value that can be represented in a double), causing an exception to be thrown.