Skip to content.

kagome.lab.tkikuchi.net

Sections
Personal tools
You are here: Home » Members » tkikuchi's Home » 授業 » 専門コア情報処理演習(2006) » 解答例10
Views

解答例10

Document Actions

問題1

  • lim(x→0) sin(x)/x は 1.0 である。しかし,sin(0.0)/0.0 を計算することはできない。x に小さい値を入れて計算してみて,1.0 に近づいていく様子を見てみよう。 この問題をプログラム(q1.py)で解きなさい。但し、最初の x の値を 1.0 とし、繰り返すとき x の値は前の値の半分(1/2) にすること。
  • #!/usr/bin/env python
    from math import *
     
    x = 1.0
    while 1:
        y = sin(x)/x
        print '%.10e %.15e' % (x, y)
        if y == 1.0:
            break
        x = x / 2.
    
  • print のところは、フォーマット無しでもよい (print x, y)

問題2

  • 二次方程式の解を計算するプログラム q2.py を作りなさい。平方根の計算には math.sqrt() を使うことができる。
  • #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # 二次方程式
    import math
     
    print '二次方程式の係数を入れてください'
    a = input('a? ')
    b = input('b? ')
    c = input('c? ')
    d = b * b - 4 * a * c
    if a == 0:
        if b == 0:
            print '解がありません'
        else:
            print 'a = 0 なので一次方程式です'
            print '解は', -float(c)/b, 'です'
    elif d < 0:
        print '実数解はありません'
    elif d == 0:
        print '解は', -float(b)/(2*a), 'です'
    else:
        e = math.sqrt(d)
        x1 = (-b + e)/(2*a)
        x2 = (-b - e)/(2*a)
        print '解は', x1, 'と', x2, 'です'
    
  • この解答例では、問題の参考実行例に無い場合わけもしているが、d < 0 とそれ以外だけでもよい。
  • 判別式の計算結果は後で利用するので、別の変数に入れておいたほうがよい。
Created by tkikuchi
Last modified 2006-12-25 09:27
 

Powered by Plone

This site conforms to the following standards: