Home > Blockchain >  Trigonometric Equation only works with specific input ( 5 ) doesn't work with other inputs
Trigonometric Equation only works with specific input ( 5 ) doesn't work with other inputs

Time:08-17

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.

CodePudding user response:

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).

  • Related