math.cos(x) not returning correct value?

拜拜、爱过 提交于 2020-07-03 16:59:10

问题


I just started using python, and am having difficulty with a very basic program. I want to calculate the cosine of -20 degrees. It is my understanding that the default value is in radians, so this is the following code i tried:

import math 


print math.cos(math.degrees(-20))

This outputs (-.7208...), where the answer is actually (.9397...). I'm sure this has a pretty basic solution but I've tried so many different things and it will not output the correct results. Thanks in advance!


回答1:


Per the Python documentation:

math.degrees(x)

Convert angle x from radians to degrees.

That means you are attempting to convert -20 radians to degrees which isn't desired.

Also per the documentation:

math.cos(x)

Return the cosine of x radians.

This means math.cos finds the cosine of the passed argument in radians, not degrees. That means your code currently changes -20 radians to degrees, then finds the cosine of that as if it were radians... you can see why that's a problem.

You need to convert -20 degrees to radians, and then find the cosine. Use math.radians:

math.cos(math.radians(-20))



回答2:


You need to input in radians, so do

math.cos(math.radians(-20))

math.radians(-20) converts -20 degrees to radians.




回答3:


math.degrees takes a number of radians and produces a number of degrees. You need the opposite conversion - you have a number of degrees, and you need to produce a number of radians you can pass to math.cos. You need math.radians:

math.cos(math.radians(-20))


来源:https://stackoverflow.com/questions/39694465/math-cosx-not-returning-correct-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!