2 kyu
Finding Derivatives
19MikChan
Description:
The task
Create a function differentiate
which takes a string
as an argument and creates another 3 complex-argument functions which are:
- the function in the string itself;
- its first derivative;
- its second derivative.
The input
The input is a string that is described by the following BNF:
<constant> ::= [0-9]+ ( "." [0-9]+ )?
<variable> ::= "x"
<func_name> ::= "sin" | "cos" | "tan" | "cot" | "log"
<expression> ::= <term> ( ( "+" | "-" ) <term> )*
<term> ::= <factor> ( ( "*" | "/" ) <factor> )*
<factor> ::= <basic> ( "^" <basic> )*
<func_call> ::= <func_name> "(" <expression> ")"
<basic> ::= <constant> | <variable> | <func_call> | ( "(" <expression> ")" )
Assume all inputs to be valid.
The output
The outputs are the parsed function, its first and second derivatives. All of them should receive and return a complex number. For example:
const auto f = differentiate("2 * x^3");
std::get<0>(f)({ 2, 2 }) == (-32, 32)
/*
Because:
f(x) = 2 * x^3
f(2 + 2i) = 2 * (2 + 2i)^3 = -32 + 32i
*/
std::get<1>(f)({ 2, 2 }) == (0, 48)
/*
Because:
f'(x) = (2 * x^3)' = 6 * x^2
f'(2 + 2i) = 6 * (2 + 2i)^2 = 48i
*/
std::get<2>(f)({ 2, 2 }) == (24, 24)
/*
Because:
f''(x) = (6 * x^2)' = 12 * x
f''(2 + 2i) = 12 * (2 + 2i)^2 = 24 + 24i
*/
Notes
- Sometimes the input function or its derivatives will be impossible to evaluate for some arguments (e.g.
log(0)
). This is still considered valid input. Though, the return value of the returned function will not be tested if this is a case. - Spaces are allowed between any tokens except inside of
<constant>
. E.g.x + 1
andcos ( 1 / 2 )
are valid, but2. 0
or2 1
are not. - PEMDAS rule is applied.
- Exponential towers must be handled the same way Wolfram Alpha does. E.g.
a^b^c
isa^(b^c)
, not(a^b)^c
. log
is the natural logarithm.- Trigonometric functions arguments are in radians, not degrees.
The real task
Have fun :)
Mathematics
Algorithms
Parsing
Similar Kata:
Stats:
Created | Apr 27, 2021 |
Published | Apr 28, 2021 |
Warriors Trained | 250 |
Total Skips | 54 |
Total Code Submissions | 930 |
Total Times Completed | 19 |
C++ Completions | 19 |
Total Stars | 39 |
% of votes with a positive feedback rating | 79% of 7 |
Total "Very Satisfied" Votes | 4 |
Total "Somewhat Satisfied" Votes | 3 |
Total "Not Satisfied" Votes | 0 |
Total Rank Assessments | 4 |
Average Assessed Rank | 2 kyu |
Highest Assessed Rank | 2 kyu |
Lowest Assessed Rank | 3 kyu |