2015年11月29日日曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More! (Amit Saha (著)、No Starch Press)のChapter 2.(Visualizing Data with Graphs)、Programming Challenges #5: Exploring the Relationship Between the Fibonacci Sequence and the Golden Ratio(No. 1472)を解いてみる。

#5: Exploring the Relationship Between the Fibonacci Sequence and the Golden Ratio(No. 1515)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt

def fibo(n):
    if n == 1:
        return [1]
    if n == 2:
        return [1, 1]
    a = 1
    b = 1
    series = [a, b]
    for i in range(n):
        c = a + b
        series.append(c)
        a = b
        b = c
    return series

def draw_graph(x, y):
    plt.title('Ratio between consecutive Fibonacci numbers')
    plt.plot(x, y)
    plt.xlabel('No.')
    plt.ylabel('Ratio')

    plt.savefig('golden_ratio.svg')
    plt.show()
    
if __name__ == '__main__':
    n = 100
    nums = fibo(n)
    x = range(n)
    draw_graph(x, [nums[0]] + [nums[i] / nums[i - 1] for i in range(1, n)])

入出力結果(Terminal, IPython)

0 コメント:

コメントを投稿

Comments on Google+: