Why does this function return NaN?
Hi, I am writing a Sin function in C#, the function uses the taylor series algorithm to calculate the sine of a given angle. However, when given the angle, it returns NaN. Reason as to why?
13 Replies
This uses the exactly same algorithm and steps as the one I have written in Python and that works just fine.
Around i < 20 causes the issue, however at i <5 - 10, the function just doesn't give a percise answer
Feel free to ping me if someone finds a solution
have you stepped through with a debugger to see where the NaN first gets introduced?
this is all i get
doesnt really tell me where NaN occurs when i debug it
$debug
Tutorial: Debug C# code and inspect data - Visual Studio (Windows)
Learn features of the Visual Studio debugger and how to start the debugger, step through code, and inspect data in a C# application.
you need to set breakpoints and inspect the values of the variables at different points in the code's execution
I should be able to do this in VSC right? Because thats what im using rn not VS
i haven't tried to use a debugger in VSC, but if you can there should be resources online about it
worst case you can do some good old
Console.WriteLine()
debuggingyeah the vsc debugger is just shit :/
doesnt tell me anything
just use VS if that's an option
Possibly due to the radian conversion is invalid. For instance, negative degrees
just a wild guess, you should debug it and see the conversion value
the problem is that your IntFactorial overflows
to be clear, an
int
can hold 12! but not 13!
a ulong
can hold 20! but not 21!
because your loop goes up to i = 20, you try evaluating factorials which produce results that do not fit into int
this would cause accuracy issues in general, but unfortunately large enough factorials are congruent with 0 mod 2^31, so e.g. IntFactorial(2 * 17 + 1) = 0
this means that you get a divide-by-zero when computing term
, which introduces Infinity. the divide-by-zero keeps producing Infinity, but since you alternate signs, you end up with -Infinity + Infinity, which is NaN
you can fix this by not doing 20 iterations (e.g. limit i <= 5
)
if you change it to a ulong
instead of an int
(i'm assuming it's an int
, you did not really share the code for that), then you can change it to i <= 9
and, to be clear, the VS Code debugger is fine. i debugged this issue using italright ima try to change that