There was a post about this before: http://www.daniweb.com/forums/thread88472.html
but no code in it, this is the code I have written and it calculates the sine of x, but not exactly what I was asked to do, I have set counter to 15, and there should be no counter, it should stop when fsum/sum2 < 1e-8. I think this should be done with a do while function, I have tried putting the whole thing inside one but it doesnt work that way, since it finishes the counter first and then goes to the while with the final result. Someone please help.

#include <iostream.h>
#include <conio.h>
#include <stdio.h>

int main()
{
clrscr();

double x,sum,mult=0,count,sign=1,fsum,count2,mult2=3,sum2=2,fres=0;
cin>>x;

sum=x;
for (count=1;count<15;count=count+2) //first loop for x-x^3+x^5-x^7...
{
sign=-sign;
mult=x*sum;
sum=x*mult;
fsum=sum;
fsum=fsum*sign;//changes sign, 1st one + 2nd one - 3rd one + ....
for (count2=count2;count2<count;count2++)//second loop for 3! 5! 7!...
{
sum2=sum2*mult2;
mult2++;
}
cout<<fsum/sum2<<endl;//-x^3/3! +x^5/5! ...
fres=fres+(fsum/sum2); //final result here is sine of x, still gotta add x^1
}
cout<<x+fres<<endl;//its +x because at the and gotta add x^1, loop calculates starting
//from -x^3

getch();
return 0;
}

Recommended Answers

All 15 Replies

Indentation will make the code easier to follow. I'd probably approach the problem like this:

double sinx = 0;
double term;
double tolerance = 0.00000001;
double x;
// code
 
do
{
     // code
     // calculate term
     sinx = sinx + term;
     // code
}
while (fabs (term) > tolerance);

cout << "The sine of " << x << " is " << sinx;

ok, I think I got it, just replaced the for loops, and put the code inside a do while, but now the problem is 'term' takes both positive and negative values, so what should i put on the while? no matter if < or > still going to only execute the code once

What's a problem? Use double fabs(double) from <math.h>.

Hadnt ever heard of that function before, probably not allowed to use it.

It's not that difficult to implement one by yourself:

double myfabs(double x) {
     if(x>=0) {
          return ***;
     }
     else {
          return ***;
     }
}

It should be easy for you to figure out what you have to return in each case ;-)

Hadnt ever heard of that function before, probably not allowed to use it.

Never repeat this statement, it's funny ;)
Probably, you may use main function...
That's why C++ is not pascal:

inline double Fabs(double x) { return x<0.0?-x:x; }

Better forget that silly, unnecessary, nonstandard and nonportable clrscr...

ok, that do while didn't do the trick. I couldn't get it to work. But I got it to work other way, with a while and a for, this is the final code.

double x, sum, mult=0, count, sign=1, fsum, count2, mult2=2, sum2=1, fres=0;
cin>>x;

sum=x;
while (sum/sum2>1e-8)
{
sign=-sign;
mult=x*sum;
sum=x*mult;
fsum=sum;//sum always remains positive and i make new variable 'fsum' for the negative
fsum=fsum*sign;//changes sign, 1st one + 2nd one - 3rd one + ....
count=count+2;
for (count2=count2;count2<count;count2++)//second loop for 3! 5! 7!...
{
sum2=sum2*mult2;
mult2++;
}
cout<<fsum<<" / "<<sum2<<" = "<<fsum/sum2<<endl;//-x^3/3! +x^5/5! ...
fres=fres+(fsum/sum2); //final result here is sine of x, still gotta add x^1
}
cout<<x+fres<<endl;//its +x because at the and gotta add x^1, loop calculates starting
//from -x^3

not sure if anyone was interested in this or not but though i would post it.

what it does is first processes the while loop, inside the while loop count is added 2 every time the loop executes, then goes to for loop and runs as long as count2<count, which is always twice, finishes with for and goes back to while, divides sum/sum2 and this is the value to make the loop stop executing when its result is lower than 1e-8.

Now a problem is, how do i make it stop exactly at 1e-8? because what it does now is when the value is <1e-8 runs once more and then stops. help with this please, have always had a problem with this. For a fibonacci series I used && and the other statement, but it was easier there because its well, a fibonacci series. dont know how to properly explain it.

The do-while loop does do the trick. I don't know what you did or whether you used fabs or wrote your own or what, but you can't do this problem without using it or something close. You were correct originally in trying to get rid of the for-loop. You do that by using a while loop or a do-while loop and exiting the loop by comparing some value to your tolerance, which it appears you are doing anyway. If your while or do-while loop doesn't work, you need to change it so it does work, not revert to a for-loop. I don't understand what this for-loop is doing.

Anyway, the program either doesn't work or I'm not using it correctly. I typed in 0.5236 (30 degrees in radians) and I got an answer/display of 0.410938 instead of 0.5, which is the sine of 30 degrees.

Apart from anything else:
1. Try sin(0) with your code...
2.

Now a problem is, how do i make it stop exactly at 1e-8? because what it does now is when the value is <1e-8 runs once more and then stops. help with this please, have always had a problem with this.

It's not only pseudo-problem; it's a sign of a serious misunerstanding of a floating point arithmetics. No such animal as "exact 1e-8" value in the double type domain. Floating point numbers are approximations of real numbers. Look at:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
http://en.wikipedia.org/wiki/Floating_point
3. Use code indentation. It's a very hard job to read (to understand, to improve, to debug etc) your code. Use code tag correctly:
[code=cplusplus] source code

[/code]
4. Look at the "reference" implementation ;):

const double eps = 1e-8;
const double pi2pi = 6.28318530717958648;

const double pi  = 3.14159265358979323846;

inline double dabs(double x) { return x < 0.0?-x:x; }

double sine(double x)
{
    // Prevent overflow, do faster, more accurately...
    if (dabs(x) > pi2pi) {        
        double npi;
        modf(x/pi2pi,&npi); // from <math.h>
        x -= pi2pi * npi;
    } // It's not so easy to implement modf analog...
    
    // Prevent underflow and divide by zero
    if (dabs(x) < eps)
        return x;

    // Ooh! Let's go...
    double mx2 = -x*x;
    double n  = 0.0;
    double r = x;

    do {
        n += 2.0;
        x *= mx2/(n*(n+1.0));
        r += x;
    } while (dabs(x/r) > eps);

    return r;
}

int main()
{
    double y;
    double x = pi/6.0;
    y = sine(x);
    std::cout << setprecision(16) << y << std::endl;
	return 0;
}

Don't bring this code to your teacher (do you know why? ;) ). Try to understand its core loop which is typical for recurrent series members calculation. Pay attention to parameter check up codes...

while (( sum/sum2 >0 && sum/sum2>1e-8 )|| (sum/sum2<0 && sum/sum2<-1e-8))

added that to calculate negative angles as well, hmm I dont know why it isnt working for you, it works for me i tried inputting the same number as you did and i got the right answer 0.5000001. Tried 0 as well, answer is 0. and Im a newbie so I dont even know what indentation is. My native language is not english so that dont help either. And about using for loop, I think I do need it, because its 3! 5! 7!, not recurrent numbers like 2! 3! 4! so there needs to be a for loop so that it executes twice before giving the result. I find the code easy to understand, i mean a while loop, a for loop inside it and at the end of the while loop the result is calculated.

while (( sum/sum2 >0 && sum/sum2>1e-8 )|| (sum/sum2<0 && sum/sum2<-1e-8))

added that to calculate negative angles as well, hmm I dont know why it isnt working for you, it works for me i tried inputting the same number as you did and i got the right answer 0.5000001. Tried 0 as well, answer is 0. and Im a newbie so I dont even know what indentation is. My native language is not english so that dont help either. And about using for loop, I think I do need it, because its 3! 5! 7!, not recurrent numbers like 2! 3! 4! so there needs to be a for loop so that it executes twice before giving the result. I find the code easy to understand, i mean a while loop, a for loop inside it and at the end of the while loop the result is calculated.

Here's the program I ran. It's your code. I added code to make it run and some explanation to the display, but it's the same code. I think I am reading the output correctly. If not, you should get rid of the extraneous output and add some words to tell the user what to enter and what the answer is. Run it and see what you get when you enter 0.5236. I don't get 0.5.

#include <iostream>
using namespace std;


int main ()
{
    double x, sum, mult=0, count, sign=1, fsum, count2, mult2=2, sum2=1, fres=0;
    cout << "Enter angle in radians: ";
    cin>>x;
    
    sum=x;
    while (sum/sum2>1e-8)
    {
        sign=-sign;
        mult=x*sum;
        sum=x*mult;
        fsum=sum;//sum always remains positive and i make new variable 'fsum' for the negative
        fsum=fsum*sign;//changes sign, 1st one + 2nd one - 3rd one + ....
        count=count+2;
        
        for (count2=count2;count2<count;count2++)//second loop for 3! 5! 7!...
        {
            sum2=sum2*mult2;
            mult2++;
        }
        cout<<fsum<<" / "<<sum2<<" = "<<fsum/sum2<<endl;//-x^3/3! +x^5/5! ...
        fres=fres+(fsum/sum2); //final result here is sine of x, still gotta add x^1
    }
    cout<<"sine of " << x << " equals " << x+fres<<endl;//its +x because at the and gotta add x^1, loop calculates starting
    //from -x^3

     cin.get ();
     cin.get ();
     return 0;
}

yup, ran the same code you pasted and when i enter 0.5236 the answer is 0.500001, Im using Turbo C++, so I had to replace using namespace std for #include <conio.h>, but other than that everything else was just the same

yup, ran the same code you pasted and when i enter 0.5236 the answer is 0.500001, Im using Turbo C++, so I had to replace using namespace std for #include <conio.h>, but other than that everything else was just the same

OK, I see what the difference is. Turbo C++ must initialize variables to 0 automatically. Dev C++ doesn't. You should initialize count and count2 to 0 before using them. Don't assume the compiler will do it for you because many will not. After doing those initializations explicitly, I get the correct answer.

in this code what does tolerance mean?

in this code what does tolerance mean?

A lot of algorithms get closer and closer estimates of whatever is to be calculated with every iteration. "tolerance" is how close you need the estimate to be to the real answer. You make the program stop when it gets "close enough". "Close enough" is the tolerance.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.