1

I am writing a function in C that returns the radius of an ellipse at a given angle with a given length and width; Basically writing this calculation in C:

enter image description here

Unfortunately the platform does not support math.h however there are sin and cos functions built in that I can use.

How do I write this calculation in C and store it in an int?

I have tried:

int theta = 90;
int a = 164;
int b = 144;

float aa = (((a^2) * ((sin_lookup(DEG_TO_TRIGANGLE(theta)))^2)) +
            ((b^2) * ((cos_lookup(DEG_TO_TRIGANGLE(theta)))^2))) /
           (TRIG_MAX_ANGLE^2);

float result = (a * b) / (my_sqrt(aa));
int value = (int)result;
Ziezi
  • 6,049
  • 3
  • 34
  • 45
Chris Schlitt
  • 411
  • 4
  • 17

1 Answers1

7

Easy enough

int getRadius(double a, double b, double theta)
{
     double s = sin(theta),
            c = cos(theta);
     return (a * b) / sqrt((a*a)*(s*s)+(b*b)*(c*c))
}

Though I'm not sure why you want to return an int. You'll loose a lot of precision.


The ^ operator is not the way to do powers. It's actually a bitwise XOR. This is a common mistake new (C) programmers make. math.h has a function pow() for calculating powers, but you said you can't use math.h. These values are only raised to the second power, so it's pretty easy to just multiply it manually.

PC Luddite
  • 5,551
  • 6
  • 18
  • 38
  • instead of creating 2 double values I would use macro or make my own pow() function. Just suggestion otherwise I think your answer is perfect. –  Oct 10 '15 at 03:59
  • @GRC If `pow` isn't already defined, that's probably a good way to do it, but just in case their math library defined `pow`, I avoided it. – PC Luddite Oct 10 '15 at 04:02
  • Probably want the return as `double` -- `int` really isn't that exciting (not to mention integer math and all....) – David C. Rankin Oct 10 '15 at 04:22
  • 1
    @DavidC.Rankin The question specifically requested `int`, otherwise I completely agree. `int` isn't going to tell you a whole lot. – PC Luddite Oct 10 '15 at 04:46
  • I gotcha, just seems so counter-intuitive. – David C. Rankin Oct 10 '15 at 06:45
  • Thanks @PCLuddite! I used a slightly modified version of your code, and it only returns an approximation. However that is all I needed. Here it is: https://gist.github.com/chrisschlitt/cf9b77c64492ca376e54 Also, I had to use an int because the draw command I was using to draw a line required integers as an input – Chris Schlitt Oct 11 '15 at 06:00