square root of a number with recursion - c++

#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;
}

Related

is there any methods can do round(a, n) in c++?

I want to round a float number.
in python, i have:
round(x, 2) # 3.1415 -> 3.14
but in c++, i find round function can only round to integer.
Is there any similar method in c++?
AFAIK the standard library provides no such function, but it shouldn't be too hard to roll out your own:
#include <iostream>
#include <cmath>
// fast pow for int, credit to https://stackoverflow.com/a/101613/13188071
int ipow(int base, int exp)
{
int result = 1;
while (true)
{
if (exp & 1)
result *= base;
exp >>= 1;
if (exp == 0)
break;
base *= base;
}
return result;
}
double round_prec(double n, int prec)
{
return std::round(n * ipow(10, prec)) / ipow(10, prec);
}
int main()
{
std::cout << round_prec(3.1415, 2) << '\n';
}
Output:
3.14
This is, however, a bit of a roundabout way of doing it, there's probably a better way that I don't know of.
You can use the built-in round functions and some scientific notation.
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
float x = 3.14159;
int val = 2;
x = round(x * pow(10, val)) / pow(10, val);
cout << x << endl;
return 0;
}

My C++ program has trouble calculating this series for Euler's number

Here is the C++ program i wrote to solve the above series:
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int factorial(int a)
{
if (a > 1)
return a * factorial(a - 1);
else
return 1;
}
float series(float x, int n, float b)
{
if (abs(pow(x, n) / factorial(n)) < pow(10, -6) || abs(pow(x, n) / factorial(n)) == pow(10, -6)) { return b; }
else return b = (pow(x, n) / factorial(n)) + series(x, n + 1, b);
}
int main()
{
float x;
cout << "Enter x: "<<endl;
cin >> x;
cout << "E^x = " << series(x,0,0);
system("pause");
return 0;
}
It works fine when abs(x) < 2 but when abs(x) >= 2 this error appears:
Unhandled exception at 0x00F02539 in 33b.exe: 0xC00000FD: Stack
overflow (parameters: 0x00000001, 0x00F22FF8). occurred
I want to know why does this happen and how can i fix it?
Your problem is too deep recursion. Consider loop instead.
float series(float x)
{
const float epsilon = 1e-6f;
double error = 1;
double res = 1.f;
int iter = 1;
while (abs(error) > epsilon) {
error *= (x / iter++);
res += error;
cout << error << endl;
}
return res;
}
int main()
{
cout << "E^x = " << series(3);
system("pause");
return 0;
}
To be clearer about what happens:
When you call a function inside another function, the context of the parent function is saved to make room for the new context. When you make millions of inception, the memory stack in charge to save these context is full and overflows.
This is a Stack Overflow.
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int factorial[200];
int Factorial(int a)
{ if(a>0){
factorial[a]=a * factorial[a-1];
return factorial[a];
}
else
factorial[a]=1;
return 1;
}
double series(double x, int n, double b)
{ double temp=(abs(pow(x, n)) / Factorial(n));
if (temp <= 0.000001) { return b; }
else return (temp + series(x, n + 1, b));
}
int main()
{
float x;
cout << "Enter x: "<<endl;
cin >> x;
cout << "E^x = " << series(x,0,0);
system("pause");
return 0;
}
umm this solution is working. all i did was i took your code removed abs(pow(x, n) / factorial(n)) wherever its repeating and intialised to a new variable temp. then instead of < || == u can directly put <=. and rather than invoking a a function to calculate .000001 every time you could just give that value to reduce time further. however i believe that the reason why the code may not have worked is too much recursion. so for factorials i used dynamic programming to reduce its complexity. the above code is working perfectly fine.

Multiplying a digit of a number with its current position and then add it with the others using recursion

the point of this exercise is to multiply a digit of a number with its current position and then add it with the others. Example: 1234 = 1x4 + 2x3 + 3x2 + 4x1 .I did this code successfully using 2 parameters and now i'm trying to do it with 1. My idea was to use - return num + mult(a/10) * (a%10) and get the answer, , because from return num + mult(a/10) i get the values 1,2,3,4- (1 is for mult(1), 2 for mult(12), etc.) for num, but i noticed that this is only correct for mult(1) and then the recursion gets wrong values for mult(12), mult(123), mult(1234). My idea is to independently multiply the values from 'num' with a%10 . Sorry if i can't explain myself that well, but i'm still really new to programming.
#include <iostream>
using namespace std;
int mult(int a){
int num = 1;
if (a==0){
return 1;
}
return ((num + mult(a/10)) * (a%10));
}
int main()
{
int a = 1234;
cout << mult(a);
return 0;
}
I find this easier and more logically to do, Hope this helps lad.
int k=1;
int a=1234;
int sum=0;
while(a>0){
sum=sum+k*(a%10);
a=a/10;
k++;
}
If the goal is to do it with recursion and only one argument, you may achieve it with two functions. This is not optimal in terms of number of operations performed, though. Also, it's more of a math exercise than a programming one:
#include <iostream>
using namespace std;
int mult1(int a) {
if(a == 0) return 0;
return a % 10 + mult1(a / 10);
}
int mult(int a) {
if(a == 0) return 0;
return mult1(a) + mult(a / 10);
}
int main() {
int a = 1234;
cout << mult(a) << '\n';
return 0;
}

Find root without while and for loop

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.

C/C++ - Iteration counter for Newton's Method

I have created a function that runs Newton's Method for approximating the solution to a function (defined as f). My function returns the better approximation for the root just fine, however it will not display the number of iterates performed in the function properly.
Here is my code:
#include <stdio.h>
#include <math.h>
#include <cstdlib>
#include <iostream>
double newton(double x_0, double newtonaccuracy);
double f(double x);
double f_prime(double x);
int main()
{
double x_0;
double newtonaccuracy;
int converged;
int iter;
printf("Enter the initial estimate for x : ");
scanf("%lf", &x_0);
_flushall();
printf("\n\nEnter the accuracy required : ");
scanf("%lf", &newtonaccuracy);
_flushall();
if (converged == 1)
{
printf("\n\nNewton's Method required %d iterations for accuracy to %lf.\n", iter, newtonaccuracy);
printf("\n\nThe root using Newton's Method is x = %.16lf\n", newton(x_0, newtonaccuracy));
}
else
{
printf("Newton algorithm didn't converge after %d steps.\n", iter);
}
system("PAUSE");
}
double newton(double x_0, double newtonaccuracy)
{
double x = x_0;
double x_prev;
int iter = 0;
do
{
iter++;
x_prev = x;
x = x_prev - f(x_prev)/f_prime(x_prev);
}
while (fabs(x - x_prev) > newtonaccuracy && iter < 100);
if (fabs(x - x_prev) <= newtonaccuracy)
{
int converged = 1;
}
else
{
int converged = 0;
}
return x;
}
double f(double x) {
return ( cos(2*x) - x );
}
double f_prime(double x)
{
return ( -2*sin(2*x)-1 );
}
To be as specific as possible, it is the line:
printf("\n\nNewton's Method required %d iterations for accuracy to %lf.\n", iter, newtonaccuracy);
that is giving me trouble. Every time I run this program it says "Newton's Method required 2686764 iterations..." however this can't be true, provided I have coded correctly (the max number of iterations my code allows is 100).
The variable iter used in main is not initialized or used in the newton function, where you use a local variable iter. You need to either pass iter to newton by reference or find a way to return it from the function.
Here is an example of a function taking some parameters by reference and modifying them:
double foo(double& initial_value, int& iterations)
{
initial_value *= 3.14159;
iterations = 42;
return initial_value/2.;
}
From the caller side:
double x + 12345.;
int iter = 0;
double y = foo(initial_value, iter);