Last active
October 17, 2023 11:14
-
-
Save arthur-flam/dfbe975b0d2cfb76da8fa1ea9648e4fe to your computer and use it in GitHub Desktop.
constrexpr exponential function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Adapted from an interview question that does the same with templates | |
// The goal was just to make the logic easier to understand with recent C++ features | |
// Don't use it in real-life LOL. | |
// | |
// It needs (1) a small wrapper to make the API cleaner (2) templates to work with any type... | |
// and in real-life you'll want more precision/speed/range/vectorization.......... | |
// | |
// To check it's indeed compile time: https://godbolt.org -std=c++17 | |
#include <iostream> | |
#include <utility> | |
constexpr std::pair<double, double> exp(double x, int n) { | |
if (n==0) | |
return std::pair<double, double>(1, 1); | |
return std::pair<double, double>( | |
exp(x, n-1).first * x / n, | |
exp(x, n-1).second + exp(x, n).first | |
); | |
} | |
int main() { | |
constexpr double x = 3; | |
constexpr int n = 10; | |
std::cout << exp(x, n).second << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment