Created
June 11, 2011 23:58
-
-
Save poochin/1021099 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| # -*- coding: utf-8 -*- | |
| ''' | |
| e^x, e^-x, cos x をテイラー展開を用いて計算する。 | |
| ''' | |
| import math | |
| factorial = lambda x: x * factorial(x - 1) if x > 1 else 1 | |
| sign = lambda i: 1 if i >= 0 else -1 | |
| def mycos(x, limit=200): | |
| ''' | |
| テイラー展開を用いて x(ラジアン)から cos を求める | |
| cos x = Σ (-1)^0 / (2n)! * x^2n | |
| ''' | |
| def monomial(x, limit): | |
| value = 1 | |
| for n in xrange(1, limit, 2): | |
| yield value | |
| value = -value * x * x / (n * (n + 1)) | |
| x = x % (2 * math.pi) | |
| return sum(monomial(x, limit)) | |
| def myexp(x, limit=200): | |
| ''' | |
| テイラー展開を用いて e^x を求める | |
| e^x = Σ (x^n / n!) | |
| e^-x = 1.0 / e^x | |
| ''' | |
| def monomial(x, limit): | |
| value = 1.0 | |
| for n in xrange(1, limit): | |
| yield value | |
| value = value * x / n | |
| return sum(monomial(abs(x), limit)) ** sign(x) | |
| def main(): | |
| for x in xrange(-40, 41, 10): | |
| print '%5.1f%14.6g%14.6g' % (x, myexp(x), math.exp(x)) | |
| for x in xrange(0, 91): | |
| xrad = math.radians(x) | |
| c1, c2 = mycos(xrad), math.cos(xrad) | |
| diff = c1 - c2 | |
| print '%d: %f, %f : [%2.5e]' % (x, c1, c2, diff) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment