I am working on a program in C that graphs a rose curve as ASCII art. The program uses custom trig functions (Taylor series to be exact):
int factorial(int n) {
int p = 1;
if (n == 0) return 1;
for (int i = 1; i < n; i ++){
p *= i;
}
return p;
}
float sine(float x, int t) {
float s = 0;
for (int i = 0; i < t; i ++) {
float n = (i%2==0 ? 1 : -1);
int d = factorial(i*2);
float m = pow(x, i*2);
s += (n/d)*m;
}
}
float cosine(float x, int t) {
float s = 0;
for (int i = 0; i < t; i ++) {
float n = (i%2==0 ? 1 : -1);
int d = factorial(i*2+1);
float m = pow(x, i*2+1);
s += (n/d)*m;
}
The t parameter denotes the number of terms, which is always 10.
And to graph the rose I use:
void point(float r, float theta) {
float fx = r*cosine(theta, TM);
float fy = r*sine(theta, TM);
int x = (int) round(fx)+50;
int y = (int) round(fy)+50;
grid[x][y] = 1;
}
...other code...
for (float theta = 0; theta < PI; theta += 0.5) {
float r = SCALE*cosine(theta*CT, TM);
point(r, theta);
The SCALE variable is the size of the rose and is defined at the top of the program. The TM variable is the number of terms in the Taylor series, and the CT variable is another parameter. It works fine using default C trig functions, but when I switch to mine it gives me a bus error, which says
make: *** [run] Bus error: 10
. This is on Mac OS X 10 by the way. The functions I wrote give me the correct values for a few numbers but just don't work here.
The Taylor series I'm using are here, and my implementation works in radians:
If you're wondering why I didn't just use the default trig functions, I'm doing this for fun and custom trig functions are part of what I want to do for this project. I'm also not the most experienced C programmer so keep that in mind.
your goniometrics computation is wasting too much CPU power
see C++ function to approximate sine using taylor series expansion
You are computing the same stuff again and again, You mix
int
andfloat
causing slow conversions ...how big is
TM
?you know factorial overflows pretty quick and on floats you can not get better precision than 5 decimals no matter what TM is anyway so I would not dare to go above
15
...you are not
return
ingfloat
value insine
andcosine
That is most likely corrupting STACK and causing your error as the rest of the code is expecting it but I do not code on your platform so I might be wrong ... Better compilers throw a warning on this ...
And of coarse without
return
your sin and cos simply does not work as even if you compute it it will not propagate the result to rest of your code. Instead you most likely got gibberish from STACK causing seemingly random numbers or evenINF
orNAN
...So simply repair your functions like this (hope I port it to C from the link above correctly):
As you can see no need for expensive operations like modulo and no calls to sub-functions nor repetitive computing of the same stuff in each iterations like you do ... Do not forget to repair your
cosine
too