使用python查找余弦 [英] finding cosine using python

查看:106
本文介绍了使用python查找余弦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个函数,该函数使用以下系列的前10个项来计算并返回角度的余弦: cosx = 1-(x ** 2)/ 2! +(x ** 4)/ 4! -(x ** 6)/ 6!....



我不能使用阶乘函数,但是我可以使用如果前一个分母是 n!,那么当前分母将是 n!(n + 1)(n + 2)。我正在尝试使用累加器循环,但是很难将其从正变为负,并且在分母方面遇到麻烦。



这是我到目前为止的内容。分母和累加器循环有帮助吗?

  def factorial(x):

if(x == 0):
返回1
返回x *阶乘(x-1)


def余弦(角度):

对于范围(2,20,2)中的i,cosx = 1
符号= -1

cosx = cosx +(符号*(角度** i))/阶乘(i)
sign = -sign
return cosx


解决方案

注意:如果您使用的是 Python2.x ,则应使用 ____________________________________ ____________除

作为文件的第一行



< hr>

一种方法是像这样替换符号

  def cos(angle ):
符号= -1
cosx = 1
对于范围(2,20,2)中的i:
cosx + =符号*(x ** i)/( i)
符号= -sign

您仍然需要正确的阶乘部分



这里是一个更简单的版本,可以根据上一个术语来计算每个术语。

  def cos(x ):
res = 0
项= 1
对于范围(1,20,2)中的i:
res + =项
项* = -x * x / i /(i + 1)
返回res


I must write a function that computes and returns the cosine of an angle using the first 10 terms of the following series: cosx = 1 - (x**2)/2! + (x**4)/4! - (x**6)/6!....

I can't use the factorial function, but i can use the fact that if the previous denominator was n!, the current denominator would be n!(n+1)(n+2). I'm trying to use an accumulator loop, but i'm having a hard time with the fact that it alternates from positive to negative and also having trouble with the denominator.

This is what I have thus far. Any help with the denominator and accumulator loop?

def factorial(x):

    if(x == 0): 
        return 1
    return x * factorial(x-1)


def cosine(angle):

    cosx = 1
    sign = -1
    for i in range(2, 20, 2):
        cosx = cosx + (sign*(angle**i))/factorial(i)
        sign = -sign
    return cosx

解决方案

Note: If you are using Python2.x, you should use

from __future__ import division

as the first line of the file


One way is to alternate the sign like this

def cos(angle):
    sign = -1
    cosx = 1
    for i in range(2,20,2):
         cosx += sign*(x**i)/(i)
         sign = -sign

You'll still need to get the factorial part correct

Here is a simpler version that calculates each term based on the previous one.

def cos(x):
    res = 0
    term = 1
    for i in range(1, 20, 2):
        res += term
        term *= -x * x/ i /(i + 1)
    return res

这篇关于使用python查找余弦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆