简体   繁体   中英

Issue in Math functions for Lua

We had given task as

Read an angle in degrees, and print the tan, cosec, sec, and cot values of that angle in the same order. To use via the rad() function, convert the angle from degrees to radians for the standard library functions.

For which we written code as

x = io.read()

radianVal = math.rad (x)

io.write(string.format("%.1f ", math.tan(radianVal)),"\n")

io.write(string.format("%.1f ", math.cosh(radianVal)),"\n")

io.write(string.format("%.1f ", math.sinh(radianVal)),"\n")

io.write(string.format("%.1f ", math.cos(radianVal)),"\n")

But output is not as expect, not sure where we went wrong

Run as Custom Input
30

Your Output (stdout)
0.6 
1.1 
0.5 
0.9 

Expected Output
0.57735026918963
2.0
1.1547005383793
1.7320508075689

Correct code which is working perfectly is

x = io.read()

function cot(radAngle)
  return 1 / math.tan(radAngle)
end

function cosec(radAngle)
  return 1 / math.sin(radAngle)
end

function sec(radAngle)
  return 1 / math.cos(radAngle)
end

local radAngle = math.rad(x)
print(math.tan(radAngle))
print(cosec(math.rad(x)))
print(sec(math.rad(x)))
print(cot(math.rad(x)))

How can you expect to get the correct result if you calculate cosh(x) instead of csc(x) ? You're using the hyperbolic cosine to calcuate the cosecant. I think it is obvious why your results are not accepted.

You use sinh(x) to calculate sec(x) and cos(x) to calculate cot(x) .

You're confusing mathematical functions. That's not a Lua programming problem.

I suggest you spend a few hours on researching trigonometric functions.

https://en.wikipedia.org/wiki/Trigonometric_functions

Such values are calcuated using the correct formula or function. Not by using any function of the math library that has a similar name.

cosh is deprecated since Lua 5.3 btw.

You can use math.tan to calculate the tangens of your angle.

For secant, cosecant and cotangens you'll have to implement your own functions.

Also note that the number of decimals might cause issue in result validation. Make sure it is ok to round to 1 decimal.

Example:

There is no function to calculate the cotangent of an angle. So we define one.

function cot(radAngle)
  return 1 / math.tan(radAngle)
end

local radAngle = math.rad(30)
print("tan(30°):", math.tan(radAngle))
print("cot(30°):", cot(math.rad(30)))

->
tan(30°):   0.57735026918963
cot(30°):   1.7320508075689

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM