0

I try to write code for that calculation angles from lengths of triangle. formula is cos(a)=b^2+c^2-a^2/2bc. (Triangle is here)

angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / 2 * length2 * length3)* 180 / 3.14153;
angle2 = acosf((powf(length1,2) + powf(length3,2) - powf(length2,2)) / 2 * length1 * length3)* 180 / 3.14153;
angle3 = 180 - (angle2 + angle1);

Everything is float. When entered 5-4-3 inputs outcome this.

angle one is 90.0018
angle two is nan
angle three is nan

changing order doesn't matter, only gives output for 5.

Dominique
  • 16,450
  • 15
  • 56
  • 112
garyK42
  • 13
  • 3
  • 1
    First of all, if you want to do floating-point arithmetic use `double` instead of `float`. There haven't been a need to use `float` on normal PC-like systems for a long time. Secondly, see [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Some programmer dude Aug 17 '22 at 11:26
  • If my math is correct, `angle2` is trying to take arccos(7738), that's quite of out domain for that function – Yksisarvinen Aug 17 '22 at 11:33
  • Are you missing parantheses around `2 * length1 * length3` maybe? – Yksisarvinen Aug 17 '22 at 11:35
  • 2
    Also, `powf` is good for non integral exponents like 2.64. To compute x squared, use `x * x` – Jeffrey Aug 17 '22 at 11:38
  • Pi is about 3.14159 not 3.14153? Or 3.141593? Or did you mean digits 767883 and the following from Pi? – Sebastian Aug 17 '22 at 15:45

1 Answers1

2

You are doing:

angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / 2 * length2 * length3)* 180 / 3.14153;

You should be doing:

angle1 = acosf((powf(length2,2) + powf(length3,2) - powf(length1,2)) / (2 * length2 * length3))* 180 / 3.14153;

Explanation: The problem is caused by the following formula, which is in fact badly written:

cos(a)=b^2+c^2-a^2/2bc
// This, obviously, is wrong because
//   you need to group the firt three terms together.
// Next to that, everybody understands that the last "b" and "c" are divisors, 
//   yet it would be better to write it as:

cos(a)=(b^2+c^2-a^2)/(2bc)

The brackets, I added in the code, are similar to the replacement of /2bc by /(2bc).

Dominique
  • 16,450
  • 15
  • 56
  • 112