When I give my n a value of 1 why does the result equal to 2 and not 3. Here is my code
#include <stdio.h>
int main()
{
int n;
float result;
scanf("%d", &n);
result = 1 + n/(2*n+1)*3/2;
while (n != 1)
{
result = result*(n-1)/(2*(n-1)+1);
n = n-1;
}
result = result * 2;
printf("%f", result);
return 0;
}
Since n is an int, the math on the right side is done as integer math, not float. Then the results is promoted to float to store into result.
result = 1 + n/(2*n+1)*3/2;
result = 1 + 1/3*3/2;
result = 1 + 1;
result = float(2);
Use float constants to get it to actually calculate as a float.
result =1.0f + n/(2.0f*n+1.0f)*3.0f/2.0f;
I am trying to count series of: 1/2 + 1/3 + 1/4 + 1/5 + ...
But I had problem with my output:
Insert how many series's number will be counted : 3 // I am input 3
Total = 1 // This is the problem, the output should shown = 1.8333
My program
#include <iostream>
#include <math.h>
using namespace std;
int recursion ( int n );
int main ()
{
int n;
cout << "Insert how many number will be counted : ";cin >> n;
cout << "Total = " << recursion(n);
}
int recursion (int a)
{
int result;
if ( a >= 1 )
{
result = 1;
}
else
{
result = ( pow ( a , -1 ) + recursion ( pow ( ( a - 1 ) , -1 ) ) );
}
return (result);
}
As others have said, use floating point types, such as double or float.
In integer division, 1/3 == 0.
Here's an iterative example:
const unsigned int NUMBER_OF_TERMS = 100;
double result = 0.0;
double denominator = 2.0;
for (unsigned int i = 0; i < NUMBER_OF_TERMS; ++i)
{
result = result + 1.0 / denominator;
denominator = denomenator + 1.0;
}
Your code should use floating point constants (with decimal points) and floating point variables (of type double or float).
Edit 1: Basic recursion
In some cases of recursion, thinking of the solution backwards may help the implementation.
For example, the series starts with 1.0/2.0. However, since the sum operation doesn't depend on order, we can start with 1.0/5.0 and work backwards:
result = 1.0/5.0 + 1.0/4.0 + 1.0/3.0 + 1.0/2.0
This allows the denominator to be used as the condition for ending the recursion.
double recursive_sum(double denominator)
{
if (denominator < 2)
{
return 0.0;
}
return recursive_sum(denominator - 1.0)
+ 1.0 / denominator;
}
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))));
}
Im trying to make a function that does division with out the / symbol
long q(int nm1, int nm2)
{
long q = 0;
while ( num1 > num2)
{
some subtraction here
}
return q;
}
the idea is to assume the input is in order and the first is to be divided by the second.
This means subtract the second from the first until the second is less then the first number.
I tried many different ways to do this but for what ever reason I cant hit it.
For now I am assuming the number is positive and wont return division by zero (I can fix that later by calling my other functions)
This means subtract the the second from the first until the second is less than the first number.
And what's the problem with that?
int div(int num, int den)
{
int frac;
for (frac = 0; num >= den; num -= den, frac++)
;
return frac;
}
What you're original post is trying to do is the Division by repeated subtraction algorithm. Have a look at Wikipedia:
The simplest division algorithm, historically incorporated into a
greatest common divisor algorithm presented in Euclid's Elements, Book
VII, Proposition 1, finds the remainder given two positive integers
using only subtractions and comparisons
while N ≥ D do
N := N - D
end
return N
Just add a counter in your while loop to keep track of the number of iterations (which is what you will want to return) and after your loop N will contain your remainder (if it is not 0 of course).
This code will work only if the num and den are integer values.
int main( int num, int den )
{
if(den==0)
{
return 1;
}
else
{
while(num!=0)
{
num = num - den;
}
}
return 0;
}
Just improving the above answer slightly.
Use modulus
long div(int num, int den)
{
int frac;
int num2 = num;
for (frac = 0; num2 >= den; num2 -= den, frac++)
;
// i needed the original num and den.
return ( (long) frac )+( num % den );
// casts frac to long then adds the modulus remainder of the values.
}
just a bit optimization: you don't want to have linear time complexity with the input value
int div(int num, int den)
{
int result = 0;
int i;
long long x;
long long y;
if (num < 0) return -div(-num, den);
if (den < 0) return -div(num, den);
if (num < den) return 0;
x = num;
y = den;
i = 0;
while((i < 32) && (x > (y << (i+1)))) i++;
for(;i>0; i++)
{
if (x > (y << i))
{
x -= y;
result += 1 << i;
}
}
return result;
}
I'am trying to expand exp(x) function to Taylor series. Here is code:
double CalcExp(){
double eps = 0.0000000000000000001;
double elem = 1.0;
double sum = 0.0;
int i = 1;
sum = 0.0;
do {
sum += elem;
elem *= x / i;
i++;
} while (elem >= eps);
return sum;
}
The problem is when I enter big X or negative X my program crashes.
And when I enter X like "0.00000000001" the result is -1.
Need advice. Thank's for help.
For big X values (around 700 and above), you'll hit the range limit for doubles (10^308) and cause an infinite loop. You can't do much about it, you should either limit X input range or use some big number library to have extended range.
Another workaround is to add this to your loop:
if (sum > 1E305) {
// we'll most likely run into an infinite loop
break;
}
Note you should handle this case outside the loop afterwards to avoid printing a very large incorrect result.
I can't reproduce the problem for 0.00000000001, this just returns 1 for me. Negative values run fine, too, although the result is wrong which seems to be an error/limitation in the algorithm. EDIT: To correct this, we can use the fact that e^-x is the same as 1 / e^x.
Code:
#include <stdio.h>
double CalcExp(double x){
double eps = 0.0000000000000000001;
double elem = 1.0;
double sum = 0.0;
bool negative = false;
int i = 1;
sum = 0.0;
if (x < 0) {
negative = true;
x = -x;
}
do {
sum += elem;
elem *= x / i;
i++;
if (sum > 1E305) break;
} while (elem >= eps);
if (sum > 1E305) {
// TODO: Handle large input case here
}
if (negative) {
return 1.0 / sum;
} else {
return sum;
}
}
int main() {
printf("%e\n", CalcExp(0.00000000001)); // Output: 1.000000e+000
printf("%e\n", CalcExp(-4)); // Output: 1.831564e-002
printf("%e\n", CalcExp(-45)); // Output: 2.862519e-020
printf("%e\n", CalcExp(1)); // Output: 2.718282e+000
printf("%e\n", CalcExp(750)); // Output: 1.375604e+305
printf("%e\n", CalcExp(7500000)); // Output: 1.058503e+305
printf("%e\n", CalcExp(-450000)); // Output: 9.241336e-308
return 0;
}
Need advice.
Try stepping through your program in a debugger to see where it's going wrong. If you don't have a debugger, insert print statements within the loop to monitor the values of variables that change.