CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 23

Threaded View

  1. #17
    Join Date
    Feb 2017
    Posts
    674

    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
    	};
    	return resfun(0.0, 1U, RAD, 1);
    }
    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.

Tags for this Thread

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured