帮我写一个函数

时间:2010-12-17 03:42:38

标签: python sage

你好,任何人都可以帮我写一个函数,计算给定x和正整数n的1 + x + x ^ 2 + ... + x ^ n并用它来计算(1 + x + x ^ 2 + ... + x ^ 10)(1 + x ^ 2 + x ^ 4 + ... + x ^ 10)x = 100?

6 个答案:

答案 0 :(得分:1)

def myfunc(x, n, step):
  if n > 0:
    return x**n + myfunc(x, n - step, step)
  return 1

myfunc(100, 10, 1) * myfunc(100, 10, 2)

答案 1 :(得分:1)

您可以使用它来计算1+x+x^2+...+x^n

lambda x, n: sum([x**y for y in range(0, n + 1)])

使用逻辑计算第二个函数。

答案 2 :(得分:1)

由于您在其上放置了一个Sage标签,因此在Sage中这是一种有趣的方式。

sage: R.<x> = PowerSeriesRing(ZZ)

将R定义为幂级数,其中x为变量。 ZZ意味着我们使用整数来表示系数。现在,让我们来看看我们可以用它做什么:

sage: R([1, 2])              # the array inside contains the coefficients 
1 + 2*x                      # for each element of the series
sage: R([1]*11)              # this gives us the first power series
1 + x + x^2 + x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^10
sage: R([1,0]*5 + [1])       # and here is our second one
1 + x^2 + x^4 + x^6 + x^8 + x^10
sage: R([1]*11).(5)          # we can evaluate these for various x values
12207031
sage: R([1]*11).subs(x=5)    # an alternate way to evaluate
12207031
sage: f = R([1]*11)*R([1,0]*5+[1])  # this constructs the desired function
sage: f(100)                   # we can evaluate it at any value

无论如何,希望你现在明白如何在Sage中做到这一点。我自己对Sage很新,但到目前为止我真的在挖它。

答案 3 :(得分:0)

你的第一个问题,

X = 2; (给定的)

N = 10; (给定的)

检查这些值是否为正值且是否需要

结果= 1;

用于:(a = 2; A&LT; = N;一++)

{

结果+ = X ^一个;

}

答案 4 :(得分:0)

我认为这是你正在寻找的功能。

def f(x, n):
    answer = 0
    for y in range(n + 1):
        answer += x ** n
    return answer

我不太了解第二部分。

答案 5 :(得分:0)

function series($x, $n) {

    $answer = 1;           

    for($i = $n; $i > 0; $i--) {

         $answer += pow($x, $i);

    }

        return $answer;
}

series(100, 10) * series(100, 10)