CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

Thread: Write a C++ program to compute Sin(x)

1. Member +   Join Date
Feb 2017
Posts
639

Re: Write a C++ program to compute Sin(x)

I've modified the code in #13 somewhat to give it a more functional touch. It's part of a learning project I have started to try and soften up my strictly object oriented code with more functional elements.

Code:
long double Sine3(const double ang, const unsigned int N) {

constexpr long double PI = 3.14159265358979323846;

auto sinmap = [PI] (long double x) { // maps x to an angle wth same sin() value inside [-PI/2 .. PI/2]
auto m = std::fmod(x, PI*2); // x is mapped on [-2PI .. 2PI]
m = (m > PI) ? m - PI*2 : (m < -PI) ? m + PI*2 : m; // then on [-PI .. PI]
return (m > PI/2) ? PI - m : (m < -PI/2) ? -PI - m : m; // finally on [-PI/2 .. PI/2]
};
const auto RAD = sinmap(ang * PI/180); // convert ang to radians and map inside [-PI/2 .. PI/2]

// recursively generates the terms of the Maclaurin sin() series and adds them up
using ResFun = std::function<long double (long double, unsigned long long int, long double, unsigned int)>;
ResFun resfun = [&resfun, RAD, N] (long double res, unsigned long long int dem, long double num, unsigned int nn) {
const auto r = res + num/dem; // add term
const auto n = nn + 2; // next
return (n >= 2*N) ? r : resfun(r, dem*n*(n-1), num*(-RAD*RAD), n); // exit or make tail recursive call
};
}
The most important change is that the iterative loop of the original has been replaced by recursion. Using recursion instead of iteration is a hallmark of the functional style. Since I've used tail recursion a good optimizing compiler should be able to turn it into iteration so the performance should be on par with the original iterative loop. What bothers me is that I don't see very many advantages with recursion, at least not in this case. Too me it looks more like a complication, verbose and convoluted.
Last edited by wolle; February 19th, 2018 at 02:49 AM.  Reply With Quote

2. Re: Write a C++ program to compute Sin(x)

Too me it looks more like a complication, verbose and convoluted.
Yeah. I've looked a little into functional programming with c++ and so far I'm left underwhelmed at the potential additional complexity required - for what seems to me at the moment for extremely little gain. There are first-class functions (basically having a function type - which has been possible since early c days - and which I've used extensively over the years), pure functions (which is really good practice anyhow - and much better now that return values are not copied!) and immutable functions (which often seem to require tortuous ways to get around - such as recursion). I get the reasons for first-class and pure functions (which I've been doing but calling it good practice not functional programming!) but I'm still struggling to understand why immutable functions.

I would be interested in any guru who has a real-word case where immutable function(s) offer any benefit over other methods.  Reply With Quote

3. Re: Write a C++ program to compute Sin(x)

Code:
auto sinmap = [PI] (long double x) { // maps x to an angle wth same sin() value inside [-PI/2 .. PI/2]
auto m = std::fmod(x, PI*2); // x is mapped on [-2PI .. 2PI]
m = (m > PI) ? m - PI*2 : (m < -PI) ? m + PI*2 : m; // then on [-PI .. PI]
return (m > PI/2) ? PI - m : (m < -PI/2) ? -PI - m : m; // finally on [-PI/2 .. PI/2]
};
as sinmap is mutable, what about

Code:
auto sinmap = [PI] (const long double x) { // maps x to an angle wth same sin() value inside [-PI/2 .. PI/2]
const auto m = std::fmod(x, PI*2); // x is mapped on [-2PI .. 2PI]
const auto m1 = (m > PI) ? m - PI*2 : (m < -PI) ? m + PI*2 : m; // then on [-PI .. PI]
return (m1 > PI/2) ? PI - m1 : (m1 < -PI/2) ? -PI - m1 : m1; // finally on [-PI/2 .. PI/2]
};
Then isn't sine3() then immutable? - but why??  Reply With Quote

4. Member +   Join Date
Feb 2017
Posts
639

Re: Write a C++ program to compute Sin(x) Originally Posted by 2kaud as sinmap is mutable, what about
You're right. That's what sinmap() should look like according to the functional paradigm. (I did it in resfun() but not in sinmap() for some inscrutable reason.)

In the lingo of a book I'm reading it's called assignment-less programming. This is an assignment,

auto m = .....;

whereas this is not, it's an evaluation of an expression making m and the right-hand side expression forever the same,

const auto m = .....;

According to the author, writing assignment-less code is as important in functional programming as it is not to use goto in structured programming. I'm not entirely convinced but hopefully it becomes obvious further down the road.
Last edited by wolle; February 21st, 2018 at 11:17 AM.  Reply With Quote

5. Re: Write a C++ program to compute Sin(x)

Which one? What's your view on it?

writing assignment-less code is as important in functional programming as it is not to use goto in structured programming
Yes, that's what I've come across as well. But what I'm not seeing is a good explanation for c++ specifically as to why. Much of what I've seen is 'this is how the xyx functional language requires it to be done'. Well for a 'pure functional' language that's fine. You learn how things are done in specific languages. For c++, I've seen this is how you can implement 'functional' programming. However what benefits does this style of programming bring to c++??????? At the moment, like you, all I'm seeing is complexity and potential performance issues.  Reply With Quote

6. Member +   Join Date
Feb 2017
Posts
639

Re: Write a C++ program to compute Sin(x) Originally Posted by 2kaud Which one? What's your view on it?
The book is called Functional Programming by MacLennan. There are two reviews at Amazon and especially the one by Rahman is on the spot. I couldn't find a preview of the book anywhere so I settled for a cheap used copy not to buy a pig in a poke. The book was published in 1989 and is a typical CS textbook but with a more accessible style than most. The reference programming paradigm is structured programming. OO is not mentioned.

I'm not planning to study the book, just browse it to build an understanding of FP without the hype and dogma often found in contemporary texts. For example I've learned that although a function may be recursively defined that doesn't mean it has to be implemented using recursion to count as FP. Needless recursion should be avoided in the name of efficiency. This nugget of information alone is worth the cost of the book to me, and there is more of the same.

I wouldn't say the book is essential but I'm glad to have it as reference. I like the tone of the author and I can extract general knowledge without having to dwell too much on technical detail. I would love this author to come back and compare and contrast FP with OO from today's perspective.

However what benefits does this style of programming bring to c++??????? At the moment, like you, all I'm seeing is complexity and potential performance issues.
I'm eagerly awaiting the release of Functional Programming in C++ by Cukic which I hope will show how and why FP may be useful to C++ programmers.

In a non-dedicated functional language such as C++ I think immutability becomes a key concept. It means the const keyword could be an important (and so far overlooked) tool to accomplish more functional code. Who writes: Functional C++ the Const Way? Last edited by wolle; February 28th, 2018 at 01:35 AM.  Reply With Quote

7. Junior Member Join Date
Feb 2018
Posts
1

Re: Write a C++ program to compute Sin(x)

Code:
#include <iostream>
#include <cmath>

using namespace std;

int Sinp(int x, int n)
{
int y = 0;
int i = 1;
int fSum = 0;
int fFactorial = -1;

while (i <= n * 2)
{
for (y = 1; y <= i; y = y + 1)
{
fFactorial = -fFactorial * y;
}

fSum = fSum + pow(x,i) / fFactorial;
i = i + 2;
}

return fSum;
}

int main(void)
{
int n = 0;
int x = 0;

cout << " Please enter the value of x. " << endl;
cin >> x;

cout << " Please enter the number of terms. " << endl;
cin >> n;

cout << Sinp(x,n) << endl;
return 1;
}
Last edited by 2kaud; February 28th, 2018 at 06:41 AM. Reason: Added code tags  Reply With Quote

8. Re: Write a C++ program to compute Sin(x)

[When posting code, please use code tags so that the code is readable and formatted. Go Advanced, select the formatted code and click '#']

Cheers!

... and this adds what to this thread discussion? It's not efficient and its not the best c++ code. What is this supposed to add to the code in post #13 and post #16?? It also doesn't compute the value correctly. The series summation for sine() is based upon the value being in radians - not degrees. So only whole integer radians can be entered - and even then the answer is incorrect. The sine(1) for 1 radian is 0.84147. But for this program the answer for 6 terms is 0 and for 10 terms is -2147483648. Last edited by 2kaud; February 28th, 2018 at 06:50 AM.  Reply With Quote

assignment, c++, function, program  Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•