Why is my while loop infinite? - c++

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if (argc != 2) {
printf("Too many arguments.\n", argc );
return 1;
}
double n;
n = atof(argv[1]);
if (n<0) {
printf("Negative argument.\n");
return 1;
}
double r;
r = n;
int iteration;
iteration = 0;
while(calcError(n,r)<1e-6) {
iteration = iteration +1;
r = (r + n/r)/2;
printf(" %d. sqrt(%f)~= %f,error=%e\n",iteration,n,r,calcError(r,n));
}
printf("sqrt(%f)=%f to six places\n",n,r);
return 0;
}
int calcError (double n, double r) {
double delta;
delta = n-r*r;
delta = delta > 0 ? delta : -delta;
return 0;
}
Running this code generates an infinite while loop. I also get a warning stating: format '%e' expects argument of type 'double', but argument 5 has type 'int' [-Wformat]. Why is this?

calcError always returns 0, so
while(calcError(n,r)<1e-6)
is as good as
while(0 < 1e-6)
or
while(true)
As for the warning, the compiler says exactly what's wrong: calcError returns an int, but the format string provided by you (%e) need a double. This will yield Undefined Behavior. Changing the return type as below will fix this issue.
Looking at your code, I think you wanted to loop as long as the error was larger than 1e-6. If that's correct, you might want to modify your calcError to be as follows:
int calcError (double n, double r)
{
double delta;
delta = n-r*r;
delta = delta > 0 ? delta : -delta;
return delta;
}
which can be shortened to
double calcError(double n, double r)
{
return fabs(n-r*r);
}
and change the condition of your loop to loop until it's smaller:
while(calcError(n,r) > 1e-6)

In your calcError() function, you have,
return 0;
So in your expression, calcError() will always be zero.
and, (0 < 1e-6) is always true.

You have while(calcError(n,r)<1e-6) and calcError always returns 0, so of course your loop will go on forever. I think you meant to have calcError return delta instead of 0.

Related

Pow(x,n) in LeetCode using C++. AddressSanitizer 33

I'm having an error that I don't know how to solve when trying to submit my solution on the Pow(x,n) problem on Leetcode.
double myPow(double x, int n)
{
if(n == 0) return 1; //Power of 0 return 1
int flag = 1;
double result;
if(n<0) flag = -1; //check if negative power
vector<double> myvec(n*flag,x); //create a vector length of the power, filled with our number x
result = accumulate(begin(myvec), end(myvec), 1.0, multiplies<>()); //multiply the elements of the vector
return flag > 0? result : 1/result;
}
The error I get is this:
==33==ERROR: AddressSanitizer: allocator is out of memory trying to allocate 0x3fffffff8 bytes
#7 0x7f44d265d82f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
==33==HINT: if you don't care about these errors you may set allocator_may_return_null=1
If I leave the "accumulate" line with a 1 instead of a 1.0, I'm getting the result as if the double x was an int (ex. 2.1^3=8). But when I'm changing it to 1.0 in order to take the decimal points from the double I get the above error.
Any thoughts?
You are allocating too much memory. You can achieve the same result by using a simple for loop.
double res = 1;
for (int i = 1; i <= n; ++i)
res *= x;
Although it might give you TLE. So you'll need a better algorithm.
I don't think this problem should be solved with std::accumulate, I might be wrong though.
This is an iterative solution, which will pass:
struct Solution {
static const inline double myPow(double x, int64_t n) {
double res = 1;
int64_t m;
if (n < 0) {
m = -n;
x = 1 / x;
} else {
m = n;
}
while (m) {
if (m & 1) {
res *= x;
}
x *= x;
m >>= 1;
}
return res;
}
};
Here is one of LeetCode's solutions:
class Solution {
public:
double myPow(double x, int n) {
long long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
double ans = 1;
double current_product = x;
for (long long i = N; i ; i /= 2) {
if ((i % 2) == 1) {
ans = ans * current_product;
}
current_product = current_product * current_product;
}
return ans;
}
};
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
For interviews:
We'd like to write bug-free and clean codes based on standards and conventions (e.g., c1, 2, c++1, 2, java1, 2, c#1, 2, python1, javascript1, go1, rust1).

with given output, how many terms are used in the program calculation?

I have the following code which calculates, for the number of terms of your choosing, the square root of 6 * [ 1 + 1/(2^2) + 1/(3^2)....1/(n^2)]. In this case, I'm going with 100 terms. If I am given what the output should be, is there a way to, using my existing code, determine how many terms were used to get to that output?
#include <stdio.h>
#include <math.h>
int main(int argc, const char * argv[]) {
long double square = 0;
for (int i = 1; i <= 100; i++) {
long double squareExp = i*i;
square += 1/(squareExp);
}
long double sixTimes = 6 * square;
long double squareRoot = sqrt(sixTimes);
printf("%.8Lf", squareRoot);
return 0;
}
I tried making it so that I take the desired output (3.141592), squaring it and dividing by 6 to negative the square root and (*6), and tried running this code:
double temp = 3.141592 * 3.141592;
double tempB = temp / 6;
printf("%f\n", tempB);
int reachedZero = 0;
int valueOfN = 0;
long double square = 0;
while (square > 0) {
int i = 1;
square -= 1/i;
i++;
if (square <= 1) {
reachedZero = 1;
valueOfN = i;
break;
}
}
printf("%i", valueOfN);
return 0;
}
I can't figure out what to do. I want to take the number (after getting rid of the square root and multiplying by 6), and subtract numbers starting with 1, then 1/4, then 1/9, then 1/16...1/(n^2) until the number becomes negative. Once that happens, I set a flag and I know how many terms I needed to reach that #. I then set that specific counter to a variable, which I can print out.
#EugeneSh. This was a working solution for me. Basically matched the pi output I was looking for with my loop, checking it each time. Could have changed the for loop to a while loop but it works fine this way.
int main(int argc, const char * argv[]) {
long double square;
for (long i = 1; i>=1; i++) {
square += 1.0/(i*i);
long double sixTimes = sqrt(6 * square);
if (sixTimes >= 3.141592) {
printf("%li", i);
break;
}
}
return 0;
}

Finding square root without using sqrt function?

I was finding out the algorithm for finding out the square root without using sqrt function and then tried to put into programming. I end up with this working code in C++
#include <iostream>
using namespace std;
double SqrtNumber(double num)
{
double lower_bound=0;
double upper_bound=num;
double temp=0; /* ek edited this line */
int nCount = 50;
while(nCount != 0)
{
temp=(lower_bound+upper_bound)/2;
if(temp*temp==num)
{
return temp;
}
else if(temp*temp > num)
{
upper_bound = temp;
}
else
{
lower_bound = temp;
}
nCount--;
}
return temp;
}
int main()
{
double num;
cout<<"Enter the number\n";
cin>>num;
if(num < 0)
{
cout<<"Error: Negative number!";
return 0;
}
cout<<"Square roots are: +"<<sqrtnum(num) and <<" and -"<<sqrtnum(num);
return 0;
}
Now the problem is initializing the number of iterations nCount in the declaratione ( here it is 50). For example to find out square root of 36 it takes 22 iterations, so no problem whereas finding the square root of 15625 takes more than 50 iterations, So it would return the value of temp after 50 iterations. Please give a solution for this.
There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:
#include <math.h>
double sqrt(double x) {
if (x <= 0)
return 0; // if negative number throw an exception?
int exp = 0;
x = frexp(x, &exp); // extract binary exponent from x
if (exp & 1) { // we want exponent to be even
exp--;
x *= 2;
}
double y = (1+x)/2; // first approximation
double z = 0;
while (y != z) { // yes, we CAN compare doubles here!
z = y;
y = (y + x/y) / 2;
}
return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}
Algorithm starts with 1 as first approximation for square root value.
Then, on each step, it improves next approximation by taking average between current value y and x/y. If y = sqrt(x), it will be the same. If y > sqrt(x), then x/y < sqrt(x) by about the same amount. In other words, it will converge very fast.
UPDATE: To speed up convergence on very large or very small numbers, changed sqrt() function to extract binary exponent and compute square root from number in [1, 4) range. It now needs frexp() from <math.h> to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp().
Why not try to use the Babylonian method for finding a square root.
Here is my code for it:
double sqrt(double number)
{
double error = 0.00001; //define the precision of your result
double s = number;
while ((s - number / s) > error) //loop until precision satisfied
{
s = (s + number / s) / 2;
}
return s;
}
Good luck!
Remove your nCount altogether (as there are some roots that this algorithm will take many iterations for).
double SqrtNumber(double num)
{
double lower_bound=0;
double upper_bound=num;
double temp=0;
while(fabs(num - (temp * temp)) > SOME_SMALL_VALUE)
{
temp = (lower_bound+upper_bound)/2;
if (temp*temp >= num)
{
upper_bound = temp;
}
else
{
lower_bound = temp;
}
}
return temp;
}
As I found this question is old and have many answers but I have an answer which is simple and working great..
#define EPSILON 0.0000001 // least minimum value for comparison
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;
}
I hope it will be helpful for future users.
if you need to find square root without using sqrt(),use root=pow(x,0.5).
Where x is value whose square root you need to find.
//long division method.
#include<iostream>
using namespace std;
int main() {
int n, i = 1, divisor, dividend, j = 1, digit;
cin >> n;
while (i * i < n) {
i = i + 1;
}
i = i - 1;
cout << i << '.';
divisor = 2 * i;
dividend = n - (i * i );
while( j <= 5) {
dividend = dividend * 100;
digit = 0;
while ((divisor * 10 + digit) * digit < dividend) {
digit = digit + 1;
}
digit = digit - 1;
cout << digit;
dividend = dividend - ((divisor * 10 + digit) * digit);
divisor = divisor * 10 + 2*digit;
j = j + 1;
}
cout << endl;
return 0;
}
Here is a very simple but unsafe approach to find the square-root of a number.
Unsafe because it only works by natural numbers, where you know that the base respectively the exponent are natural numbers. I had to use it for a task where i was neither allowed to use the #include<cmath> -library, nor i was allowed to use pointers.
potency = base ^ exponent
// FUNCTION: square-root
int sqrt(int x)
{
int quotient = 0;
int i = 0;
bool resultfound = false;
while (resultfound == false) {
if (i*i == x) {
quotient = i;
resultfound = true;
}
i++;
}
return quotient;
}
This a very simple recursive approach.
double mySqrt(double v, double test) {
if (abs(test * test - v) < 0.0001) {
return test;
}
double highOrLow = v / test;
return mySqrt(v, (test + highOrLow) / 2.0);
}
double mySqrt(double v) {
return mySqrt(v, v/2.0);
}
Here is a very awesome code to find sqrt and even faster than original sqrt function.
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f375a86 - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
x = x*(1.5f - xhalf*x*x);
x = x*(1.5f - xhalf*x*x);
x=1/x;
return x;
}
After looking at the previous responses, I hope this will help resolve any ambiguities. In case the similarities in the previous solutions and my solution are illusive, or this method of solving for roots is unclear, I've also made a graph which can be found here.
This is a working root function capable of solving for any nth-root
(default is square root for the sake of this question)
#include <cmath>
// for "pow" function
double sqrt(double A, double root = 2) {
const double e = 2.71828182846;
return pow(e,(pow(10.0,9.0)/root)*(1.0-(pow(A,-pow(10.0,-9.0)))));
}
Explanation:
click here for graph
This works via Taylor series, logarithmic properties, and a bit of algebra.
Take, for example:
log A = N
x
*Note: for square-root, N = 2; for any other root you only need to change the one variable, N.
1) Change the base, convert the base 'x' log function to natural log,
log A => ln(A)/ln(x) = N
x
2) Rearrange to isolate ln(x), and eventually just 'x',
ln(A)/N = ln(x)
3) Set both sides as exponents of 'e',
e^(ln(A)/N) = e^(ln(x)) >~{ e^ln(x) == x }~> e^(ln(A)/N) = x
4) Taylor series represents "ln" as an infinite series,
ln(x) = (k=1)Sigma: (1/k)(-1^(k+1))(k-1)^n
<~~~ expanded ~~~>
[(x-1)] - [(1/2)(x-1)^2] + [(1/3)(x-1)^3] - [(1/4)(x-1)^4] + . . .
*Note: Continue the series for increased accuracy. For brevity, 10^9 is used in my function which expresses the series convergence for the natural log with about 7 digits, or the 10-millionths place, for precision,
ln(x) = 10^9(1-x^(-10^(-9)))
5) Now, just plug in this equation for natural log into the simplified equation obtained in step 3.
e^[((10^9)/N)(1-A^(-10^-9)] = nth-root of (A)
6) This implementation might seem like overkill; however, its purpose is to demonstrate how you can solve for roots without having to guess and check. Also, it would enable you to replace the pow function from the cmath library with your own pow function:
double power(double base, double exponent) {
if (exponent == 0) return 1;
int wholeInt = (int)exponent;
double decimal = exponent - (double)wholeInt;
if (decimal) {
int powerInv = 1/decimal;
if (!wholeInt) return root(base,powerInv);
else return power(root(base,powerInv),wholeInt,true);
}
return power(base, exponent, true);
}
double power(double base, int exponent, bool flag) {
if (exponent < 0) return 1/power(base,-exponent,true);
if (exponent > 0) return base * power(base,exponent-1,true);
else return 1;
}
int root(int A, int root) {
return power(E,(1000000000000/root)*(1-(power(A,-0.000000000001))));
}

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);

Recursive function returns unexpected result

My funciton takes a number input from the user and recursively sums the number 'n' to one.
Inputting a 5 would sum 1/5 + 1/4 + 1/3+ 1/2 + 1/1.
#include<stdio.h>
#include<conio.h>
//to
float recursion(float num,float sum);
void main(void)
{
float num=5,sum=0;
//input num
printf("%d",recursion(num,sum));
getch();
}
float recursion(float num,float sum)
{
// int sum=0; every time u run it the sum is assigned 0
if( num==1)
return 1;
else
{
sum=sum+(1/num);
num--;
recursion(num,sum);
}
return sum;
}//recursion function ends
The problem is, that it is giving 0. Can anyone help, please?
You should return the result of the recursive call:
return recursion(num,sum);
instead of return sum.
Why's the printf("%d") while it's supposed to print a float? Doesn't that display an integer making it always 0 for a float less than 0?
float recursion(float num)
{
if( num==1.0f)
{
printf("1/1 = ");
return 1.0f;
}
float inverse = 1.0f/num;
printf("1/%.0f + ", num);
return (inverse + recursion(--num));
}//recursion function ends
Here's the test code:
float num=5,sum=0;
float expected = 0;
for (int i = 1; i <= num; ++i)
{
expected += 1.0f/i;
}
//input num
printf("Expected %f and got %f",expected, recursion(num));
Output:
1/5 + 1/4 + 1/3 + 1/2 + 1/1 = Expected 2.283334 and got 2.283334
Hope this helps.
float recursion(float num) {
if( num==1)
return 1;
return (1.0/num) + recursion(num - 1);
}
By the way, do not input a negative number!
#fahad: Changes in your code has been commented in the code below:
float recursion2(float num,float sum)
{
// int sum=0; every time u run it the sum is assigned 0
if( num==1)
// Vite Falcon: Needs to return sum + 1
return sum + 1.0f;
else
{
// Vite Falcon: This is not really necessary.
//sum=sum+(1/num);
float inverse = 1.0f/num;
num--;
// Vite Falcon: The new sum is returned by the recursive function and so
// should be stored and returned.
sum = recursion2(num,sum + inverse);
}
return sum;
}//recursion function ends
PS: Sorry I had to answer again because I don't know how to add multi-line code as a comment.
Use sum=sum+(1.0/num);. When you divide 1, an integer with a float, the float gets converted to integer first.
float recursion(int num) {
if (num == 0) {
return 0;
}
return 1 / num + recursion(num--);
}