def linear_search(arr, target):
"""線形探索: 配列を最初から順にチェック"""
for i in range(len(arr)):
if arr[i] == target:
return i # 要素が見つかった場合、そのインデックスを返す
return -1 # 要素が見つからなかった場合、-1を返す
def binary_search(arr, target):
"""2部探索: ソートされた配列に対して二分探索を実行"""
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid # 要素が見つかった場合、そのインデックスを返す
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # 要素が見つからなかった場合、-1を返す
def hash_search(hash_table, target):
"""ハッシュ探索: ハッシュテーブル内での検索"""
if target in hash_table:
return hash_table[target] # 要素が見つかった場合、その値を返す
return -1 # 要素が見つからなかった場合、-1を返す
# 使用例
# 線形探索
arr = [1, 3, 5, 7, 9]
target = 7
index_linear = linear_search(arr, target)
print(f'線形探索: 要素 {target} のインデックス: {index_linear}')
# 2部探索
arr_sorted = [1, 3, 5, 7, 9] # 2部探索はソートされた配列に対して使用
target = 7
index_binary = binary_search(arr_sorted, target)
print(f'2部探索: 要素 {target} のインデックス: {index_binary}')
# ハッシュ探索
hash_table = {1: 'a', 3: 'b', 5: 'c', 7: 'd', 9: 'e'}
target = 7
value_hash = hash_search(hash_table, target)
print(f'ハッシュ探索: 要素 {target} の値: {value_hash}')
def bit_shift_examples(value):
# 左シフト(2ビット分)
left_shift = value << 2
# 右シフト(2ビット分)
right_shift = value >> 2
return left_shift, right_shift
# 使用例
value = 8 # 0b1000
left_shift, right_shift = bit_shift_examples(value)
print(f'元の値: {value}')
print(f'左シフト(2ビット): {left_shift} (0b{left_shift:b})')
print(f'右シフト(2ビット): {right_shift} (0b{right_shift:b})')
def floating_point_operations(a, b):
# 基本的な演算
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
return addition, subtraction, multiplication, division
def floating_point_precision(value):
import sys
# 浮動小数点数の精度
precision = sys.float_info.dig
# 浮動小数点数の表現形式
format_value = format(value, '.15f')
return precision, format_value
# 使用例
a = 1.234567890123456
b = 2.345678901234567
# 浮動小数点演算
addition, subtraction, multiplication, division = floating_point_operations(a, b)
print(f'足し算: {addition}')
print(f'引き算: {subtraction}')
print(f'掛け算: {multiplication}')
print(f'割り算: {division}')
# 浮動小数点数の精度と表現形式
precision, format_value = floating_point_precision(a)
print(f'浮動小数点数の精度: {precision} 桁')
print(f'浮動小数点数の表現: {format_value}')
class DFA:
def __init__(self):
# 状態を定義
self.states = {'q0', 'q1', 'q2'}
# 初期状態
self.start_state = 'q0'
# 受理状態
self.accept_states = {'q2'}
# 状態遷移関数: (状態, 入力) -> 次の状態
self.transition_function = {
('q0', 'a'): 'q1',
('q0', 'b'): 'q0',
('q1', 'a'): 'q1',
('q1', 'b'): 'q2',
('q2', 'a'): 'q1',
('q2', 'b'): 'q0'
}
def process_input(self, input_string):
current_state = self.start_state
for char in input_string:
if (current_state, char) in self.transition_function:
current_state = self.transition_function[(current_state, char)]
else:
return False # 入力が無効な場合
return current_state in self.accept_states
# 使用例
dfa = DFA()
# 入力文字列をテスト
test_strings = ['ab', 'ba', 'aab', 'bba', 'aaa']
for string in test_strings:
result = dfa.process_input(string)
print(f'入力 "{string}" は受理されますか? {result}')
def calculate_mips(clock_frequency, cycles_per_instruction):
"""
クロック周波数と1命令あたりのクロックサイクル数からMIPSを計算します。
Parameters:
- clock_frequency: クロック周波数(Hz)
- cycles_per_instruction: 1命令あたりのクロックサイクル数
Returns:
- MIPS: Million Instructions Per Second
"""
# 1秒間に実行できる命令数を計算
instructions_per_second = clock_frequency / cycles_per_instruction
# MIPSを計算
mips = instructions_per_second * 1e-6
return mips
def calculate_instruction_execution_time(cycles_per_instruction, clock_frequency):
"""
1命令あたりの平均実行時間を計算します。
Parameters:
- cycles_per_instruction: 1命令あたりのクロックサイクル数
- clock_frequency: クロック周波数(Hz)
Returns:
- average_instruction_time: 平均命令実行時間(秒)
"""
# 平均命令実行時間を計算
average_instruction_time = cycles_per_instruction / clock_frequency
return average_instruction_time
# 使用例
clock_frequency = 3.0e9 # 3 GHz
cycles_per_instruction = 4 # 1命令あたり4クロックサイクル
mips = calculate_mips(clock_frequency, cycles_per_instruction)
average_instruction_time = calculate_instruction_execution_time(cycles_per_instruction, clock_frequency)
print(f'クロック周波数: {clock_frequency / 1e9} GHz')
print(f'1命令あたりのクロックサイクル数: {cycles_per_instruction}')
print(f'MIPS: {mips:.2f} MIPS')
print(f'平均命令実行時間: {average_instruction_time:.2e} 秒')
def sequential_processing_time(num_instructions, cycle_time):
"""
逐次制御の処理時間を計算します。
Parameters:
- num_instructions: 命令の総数
- cycle_time: 各命令の処理時間(秒)
Returns:
- total_time: 全体の処理時間(秒)
"""
total_time = num_instructions * cycle_time
return total_time
def pipelined_throughput(num_stages, cycle_time):
"""
パイプライン処理のスループットを計算します。
Parameters:
- num_stages: パイプラインステージの数
- cycle_time: 各ステージのサイクル時間(秒)
Returns:
- throughput: パイプライン処理のスループット(命令/秒)
"""
# 理想的なスループットは、各サイクルで1命令が処理される
throughput = 1 / cycle_time
return throughput
def pipelined_processing_time(num_instructions, num_stages, cycle_time):
"""
パイプライン処理の全体の処理時間を計算します。
Parameters:
- num_instructions: 命令の総数
- num_stages: パイプラインステージの数
- cycle_time: 各ステージのサイクル時間(秒)
Returns:
- total_time: 全体の処理時間(秒)
"""
# 各命令が全てのステージを通過するのにかかる時間
total_time = (num_instructions + num_stages - 1) * cycle_time
return total_time
# 使用例
num_instructions = 1000
cycle_time = 0.01 # 10ミリ秒
# 逐次制御の処理時間
sequential_time = sequential_processing_time(num_instructions, cycle_time)
print(f'逐次制御の処理時間: {sequential_time:.2f} 秒')
# パイプライン処理のスループット
num_stages = 5
pipelined_throughput = pipelined_throughput(num_stages, cycle_time)
print(f'パイプライン処理のスループット: {pipelined_throughput:.2f} 命令/秒')
# パイプライン処理の全体の処理時間
pipelined_time = pipelined_processing_time(num_instructions, num_stages, cycle_time)
print(f'パイプライン処理の全体の処理時間: {pipelined_time:.2f} 秒')
import numpy as np
def generate_hamming_code(data_bits):
"""
ハミング符号を生成します。
Parameters:
- data_bits: データビットのリスト(例: [1, 0, 1, 1])
Returns:
- codeword: ハミング符号化されたコードワード
"""
m = len(data_bits)
r = 0
# 追加する冗長ビットの数を決定
while (2 ** r) < (m + r + 1):
r += 1
# 初期のコードワード
codeword = [0] * (m + r)
j = 0
for i in range(1, len(codeword) + 1):
if (i & (i - 1)) == 0:
# 冗長ビットの位置に設定
continue
else:
codeword[i - 1] = data_bits[j]
j += 1
# 冗長ビットを計算して設定
for i in range(r):
parity_bit = 0
for j in range(1, len(codeword) + 1):
if j & (1 << i):
parity_bit ^= codeword[j - 1]
codeword[(1 << i) - 1] = parity_bit
return codeword
def detect_and_correct_error(codeword):
"""
ハミング符号でエラーを検出し、訂正します。
Parameters:
- codeword: 受信したコードワード(例: [1, 0, 1, 1, 0, 1, 0, 1])
Returns:
- corrected_codeword: 訂正されたコードワード
- error_position: エラーがあった位置(1-indexed)
"""
r = 0
while (1 << r) <= len(codeword):
r += 1
# エラーチェック
error_position = 0
for i in range(r):
parity_bit = 0
for j in range(1, len(codeword) + 1):
if j & (1 << i):
parity_bit ^= codeword[j - 1]
if parity_bit != 0:
error_position += (1 << i)
# エラー訂正
if error_position > 0 and error_position <= len(codeword):
codeword[error_position - 1] ^= 1
return codeword, error_position
# 使用例
data_bits = [1, 0, 1, 1]
codeword = generate_hamming_code(data_bits)
print(f'生成されたハミング符号: {codeword}')
# テスト用に故意にビットを変更
received_codeword = codeword.copy()
received_codeword[2] ^= 1 # エラーを注入
corrected_codeword, error_position = detect_and_correct_error(received_codeword)
print(f'受信したコードワード: {received_codeword}')
print(f'訂正されたコードワード: {corrected_codeword}')
print(f'エラーの位置: {error_position}')
def calculate_cache_hit_rate(cache_hits, cache_requests):
"""
キャッシュヒット率を計算します。
Parameters:
- cache_hits: キャッシュヒット数
- cache_requests: キャッシュリクエスト数
Returns:
- cache_hit_rate: キャッシュヒット率(%)
"""
if cache_requests == 0:
return 0 # リクエスト数がゼロの場合はヒット率は0%
cache_hit_rate = (cache_hits / cache_requests) * 100
return cache_hit_rate
# 使用例
cache_hits = 850
cache_requests = 1000
cache_hit_rate = calculate_cache_hit_rate(cache_hits, cache_requests)
print(f'キャッシュヒット率: {cache_hit_rate:.2f} %')
def calculate_capacity(vendor_gb):
# 販売時の1GB = 1000³ バイト
vendor_bytes = vendor_gb * 1000**3
# Windows/Macの1GB = 1024³ バイト
windows_mac_gb = vendor_bytes / (1024**3)
return windows_mac_gb
def display_capacity_comparison(vendor_gb):
windows_mac_gb = calculate_capacity(vendor_gb)
print(f"販売時の容量: {vendor_gb} GB")
print(f"Windows/Mac上での表示容量: {windows_mac_gb:.2f} GB")
# ハードディスクの販売時の容量(GB)
vendor_capacity_gb = 500 # 例として500GBのハードディスク
display_capacity_comparison(vendor_capacity_gb)
def calculate_total_average_time(seek_times, search_times, transfer_times):
# 各時間の平均を計算
average_seek_time = sum(seek_times) / len(seek_times)
average_search_time = sum(search_times) / len(search_times)
average_transfer_time = sum(transfer_times) / len(transfer_times)
# 合計平均時間を計算
total_average_time = average_seek_time + average_search_time + average_transfer_time
return total_average_time
# 例としてのシーク時間、サーチ時間、転送時間
seek_times = [8, 9, 7, 10] # 単位はミリ秒
search_times = [5, 6, 4, 7]
transfer_times = [2, 3, 2, 3]
total_average_time = calculate_total_average_time(seek_times, search_times, transfer_times)
print(f"合計平均時間: {total_average_time:.2f} ミリ秒")
def calculate_availability(uptime, downtime):
"""
システムの稼働率を計算する関数。
:param uptime: システムが稼働している時間(時間単位)
:param downtime: システムが停止している時間(時間単位)
:return: 稼働率(%)
"""
# 稼働率の計算
availability = uptime / (uptime + downtime)
# パーセンテージに変換
availability_percent = availability * 100
return availability_percent
# 例として、稼働時間と停止時間を設定(時間単位)
uptime = 1000 # 稼働時間(時間)
downtime = 5 # 停止時間(時間)
# 稼働率の計算
availability_percent = calculate_availability(uptime, downtime)
print(f"システムの稼働率: {availability_percent:.2f}%")
def calculate_transmission_time(data_size, bandwidth):
"""
データ伝送時間を計算する関数。
:param data_size: データサイズ(ビット単位)
:param bandwidth: 伝送速度(bps: ビット毎秒)
:return: データ伝送時間(秒)
"""
# データ伝送時間の計算
transmission_time = data_size / bandwidth
return transmission_time
# 例としてデータサイズと伝送速度を設定
data_size_mb = 100 # データサイズ(メガバイト)
bandwidth_mbps = 50 # 伝送速度(Mbps)
# データサイズをビットに変換(1MB = 8,000,000ビット)
data_size_bits = data_size_mb * 8 * 10**6
# 伝送速度をbpsに変換(1Mbps = 1,000,000 bps)
bandwidth_bps = bandwidth_mbps * 10**6
# データ伝送時間の計算
transmission_time = calculate_transmission_time(data_size_bits, bandwidth_bps)
print(f"データ伝送時間: {transmission_time:.2f} 秒")
def calculate_rotation_time(rpm):
"""
1回転にかかる時間を計算する関数。
:param rpm: 1分間の回転数 (Revolutions Per Minute)
:return: 1回転にかかる時間(ミリ秒)
"""
# 1分間(60秒 = 60,000ミリ秒)における1回転の時間を計算
rotation_time = 60000 / rpm
return rotation_time
def calculate_average_rotation_wait_time(rotation_time):
"""
平均回転待ち時間を計算する関数。
:param rotation_time: 1回転にかかる時間(ミリ秒)
:return: 平均回転待ち時間(ミリ秒)
"""
# 平均待ち時間は0.5回転分
return rotation_time / 2
def calculate_transfer_time(data_size_bytes, bytes_per_track, rotation_time):
"""
データ転送時間を計算する関数。
:param data_size_bytes: 転送するデータサイズ(バイト)
:param bytes_per_track: 1トラックあたりに記録できるバイト数
:param rotation_time: 1回転にかかる時間(ミリ秒)
:return: データ転送時間(ミリ秒)
"""
# データ転送時間はデータサイズ / 1トラックあたりのバイト数 * 1回転あたりの時間
transfer_time = (data_size_bytes / bytes_per_track) * rotation_time
return transfer_time
def calculate_access_time(seek_time, rotation_time, data_size_bytes, bytes_per_track):
"""
アクセス時間を計算する関数。
:param seek_time: 平均シーク時間(ミリ秒)
:param rotation_time: 1回転にかかる時間(ミリ秒)
:param data_size_bytes: 転送するデータサイズ(バイト)
:param bytes_per_track: 1トラックあたりに記録できるバイト数
:return: アクセス時間(ミリ秒)
"""
# 平均回転待ち時間を計算
avg_rotation_wait_time = calculate_average_rotation_wait_time(rotation_time)
# データ転送時間を計算
transfer_time = calculate_transfer_time(data_size_bytes, bytes_per_track, rotation_time)
# アクセス時間 = シーク時間 + 平均回転待ち時間 + データ転送時間
access_time = seek_time + avg_rotation_wait_time + transfer_time
return access_time
# 練習2と練習3の条件
seek_time_2 = 0 # シーク時間は練習2では指定されていない
seek_time_3 = 20 # ミリ秒
rpm_2 = 10800 # 練習2の回転数(回転/分)
rpm_3 = 5000 # 練習3の回転数(回転/分)
data_size_3 = 4000 # 練習3で転送するデータサイズ(バイト)
bytes_per_track_3 = 15000 # 練習3で1トラックに記録できるバイト数
# 練習2の計算
rotation_time_2 = calculate_rotation_time(rpm_2)
avg_rotation_wait_time_2 = calculate_average_rotation_wait_time(rotation_time_2)
print(f"練習2の平均回転待ち時間: {avg_rotation_wait_time_2:.2f} ミリ秒")
# 練習3の計算
rotation_time_3 = calculate_rotation_time(rpm_3)
access_time_3 = calculate_access_time(seek_time_3, rotation_time_3, data_size_3, bytes_per_track_3)
print(f"練習3のアクセス時間: {access_time_3:.2f} ミリ秒")
import ipaddress
def calculate_network_info(ip, subnet_mask):
"""
IPアドレスとサブネットマスクからネットワークアドレスとブロードキャストアドレスを計算する関数。
:param ip: IPアドレス(例:"192.168.1.10")
:param subnet_mask: サブネットマスク(例:"255.255.255.0")
:return: ネットワークアドレス、ブロードキャストアドレス
"""
# IPアドレスとサブネットマスクを組み合わせてIPネットワークオブジェクトを作成
network = ipaddress.IPv4Network(f"{ip}/{subnet_mask}", strict=False)
# ネットワークアドレスとブロードキャストアドレスを取得
network_address = network.network_address
broadcast_address = network.broadcast_address
return network_address, broadcast_address
# IPアドレスとサブネットマスクを指定
ip = "192.168.1.10"
subnet_mask = "255.255.255.0"
# ネットワークアドレスとブロードキャストアドレスを計算
network_address, broadcast_address = calculate_network_info(ip, subnet_mask)
# 結果を表示
print(f"IPアドレス: {ip}")
print(f"サブネットマスク: {subnet_mask}")
print(f"ネットワークアドレス: {network_address}")
print(f"ブロードキャストアドレス: {broadcast_address}")
def process_number():
# 順次処理: ユーザーから整数を入力してもらう
number = int(input("整数を入力してください: "))
# 選択処理: 入力された整数が正か負かを判定
if number > 0:
print(f"{number} は正の数です。")
elif number < 0:
print(f"{number} は負の数です。")
else:
print(f"{number} はゼロです。")
# 前判定繰り返し: 正の整数の場合、1からその数までの合計を計算する
if number > 0:
sum_total = 0
i = 1
while i <= number:
sum_total += i
i += 1
print(f"1から{number}までの合計は {sum_total} です。")
# メイン関数を呼び出す
process_number()
import matplotlib.pyplot as plt
def arrow_diagram(tasks, dependencies):
fig, ax = plt.subplots()
# タスクを並べる
y_pos = 1
task_positions = {}
for task in tasks:
task_positions[task] = (0.1, y_pos)
plt.text(0.05, y_pos, task, ha='right', va='center', fontsize=12)
y_pos -= 0.2
# 依存関係に基づいて矢印を描画
for task, dependency in dependencies:
start_pos = task_positions[dependency]
end_pos = task_positions[task]
ax.annotate("",
xy=(0.1, end_pos[1]), xycoords='data',
xytext=(0.1, start_pos[1]), textcoords='data',
arrowprops=dict(arrowstyle="->", lw=1.5, color="blue"))
plt.ylim(0, 1.5)
plt.xlim(0, 1)
plt.axis('off')
plt.title("Arrow Diagram")
plt.show()
# タスクのリスト
tasks = ['Start', 'Task 1', 'Task 2', 'Task 3', 'End']
# 依存関係(矢印の接続元と接続先)
dependencies = [('Task 1', 'Start'),
('Task 2', 'Task 1'),
('Task 3', 'Task 2'),
('End', 'Task 3')]
# アローダイヤグラムを描画
arrow_diagram(tasks, dependencies)
import matplotlib.pyplot as plt
import numpy as np
# EVM values: Planned Value (PV), Earned Value (EV), Actual Cost (AC), Budget at Completion (BAC)
PV = np.array([100, 200, 300, 400, 500]) # Example data for Planned Value
EV = np.array([90, 190, 280, 370, 450]) # Example data for Earned Value
AC = np.array([80, 210, 290, 380, 480]) # Example data for Actual Cost
BAC = 500 # Budget at Completion
# Calculating EVM metrics
SV = EV - PV # Schedule Variance
CV = EV - AC # Cost Variance
SPI = EV / PV # Schedule Performance Index
CPI = EV / AC # Cost Performance Index
ETC = (BAC - EV[-1]) / CPI[-1] # Estimate to Complete
EAC = AC[-1] + ETC # Estimate at Completion
VAC = BAC - EAC # Variance at Completion
# Display calculated values
print(f"Schedule Variance (SV): {SV}")
print(f"Cost Variance (CV): {CV}")
print(f"Schedule Performance Index (SPI): {SPI}")
print(f"Cost Performance Index (CPI): {CPI}")
print(f"Estimate to Complete (ETC): {ETC}")
print(f"Estimate at Completion (EAC): {EAC}")
print(f"Variance at Completion (VAC): {VAC}")
# Plotting the EVM metrics
plt.figure(figsize=(10, 6))
time = np.arange(1, len(PV) + 1)
plt.plot(time, PV, label='Planned Value (PV)', marker='o', color='blue')
plt.plot(time, EV, label='Earned Value (EV)', marker='o', color='green')
plt.plot(time, AC, label='Actual Cost (AC)', marker='o', color='red')
plt.title('Earned Value Management (EVM) Metrics')
plt.xlabel('Time Period')
plt.ylabel('Cost (in units)')
plt.legend()
plt.grid(True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# Parameters for the logistic growth model
K = 1000 # Carrying capacity (maximum population)
P0 = 10 # Initial population
r = 0.1 # Growth rate
time = np.linspace(0, 100, 500) # Time range
# Logistic growth function
def logistic_growth(t, K, P0, r):
return K / (1 + ((K - P0) / P0) * np.exp(-r * t))
# Derivative of logistic growth function
def logistic_growth_derivative(t, K, P0, r):
P = logistic_growth(t, K, P0, r)
return r * P * (1 - P / K)
# Calculate logistic growth and its derivative
population = logistic_growth(time, K, P0, r)
growth_rate = logistic_growth_derivative(time, K, P0, r)
# Plot logistic growth curve
plt.figure(figsize=(10, 6))
plt.plot(time, population, label='Logistic Growth (P(t))', color='blue', linewidth=2)
plt.plot(time, growth_rate, label='Growth Rate (dP/dt)', color='red', linestyle='--')
plt.title('Logistic Growth Curve and Its Derivative')
plt.xlabel('Time')
plt.ylabel('Population / Growth Rate')
plt.grid(True)
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# サンプルデータ生成(ここではランダムデータを使用)
np.random.seed(42)
data = np.random.normal(loc=50, scale=2, size=30) # 平均50、標準偏差2のデータ
# 管理図の要素
CL = np.mean(data) # 中心線(プロセスの平均)
UCL = CL + 3 * np.std(data) # 上方管理限界
LCL = CL - 3 * np.std(data) # 下方管理限界
# 管理図をプロット
plt.figure(figsize=(10, 6))
plt.plot(data, marker='o', linestyle='-', color='blue', label='Process Data')
# 中心線
plt.axhline(y=CL, color='green', linestyle='-', label='Center Line (CL)')
# 上方管理限界
plt.axhline(y=UCL, color='red', linestyle='--', label='Upper Control Limit (UCL)')
# 下方管理限界
plt.axhline(y=LCL, color='red', linestyle='--', label='Lower Control Limit (LCL)')
# グラフ設定
plt.title('Control Chart for Quality Management')
plt.xlabel('Sample')
plt.ylabel('Measurement Value')
plt.grid(True)
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# サンプルデータ(カテゴリとそれに対応する数値)
categories = ['Category A', 'Category B', 'Category C', 'Category D', 'Category E']
values = [50, 30, 15, 10, 5] # 各カテゴリの頻度
# データの並び替え(降順に)
sorted_indices = np.argsort(values)[::-1]
sorted_categories = [categories[i] for i in sorted_indices]
sorted_values = np.array([values[i] for i in sorted_indices])
# 累積比率を計算
cumulative_percent = np.cumsum(sorted_values) / np.sum(sorted_values) * 100
# パレート図を描画
fig, ax1 = plt.subplots(figsize=(10, 6))
# 棒グラフ(カテゴリごとの頻度)
ax1.bar(sorted_categories, sorted_values, color='C0')
ax1.set_xlabel('Categories')
ax1.set_ylabel('Frequency', color='C0')
ax1.tick_params('y', colors='C0')
# 累積比率の折れ線グラフ
ax2 = ax1.twinx()
ax2.plot(sorted_categories, cumulative_percent, color='C1', marker='o', linestyle='-', linewidth=2)
ax2.set_ylabel('Cumulative Percentage', color='C1')
ax2.tick_params('y', colors='C1')
# 累積比率に80%のラインを追加
ax2.axhline(y=80, color='red', linestyle='--', label='80% Line')
ax2.legend(loc='best')
# グラフのタイトルとレイアウト調整
plt.title('Pareto Chart with Cumulative Percentage')
fig.tight_layout()
plt.show()
# 画面数の定義
small_simple = 30
medium_normal = 40
large_normal = 20
large_complex = 10
# 作成工数の定義 (人日)
small_simple_cost = 0.4
medium_normal_cost = 0.6
large_normal_cost = 0.8
large_complex_cost = 1.2
# 画面ごとの作成工数の計算
total_creation_cost = (small_simple * small_simple_cost) + \
(medium_normal * medium_normal_cost) + \
(large_normal * large_normal_cost) + \
(large_complex * large_complex_cost)
# レビューと修正に要する工数
review_and_fix_cost = 5
# 管理工数(作業工数の20%)
management_cost = 0.2 * (total_creation_cost + review_and_fix_cost)
# 総工数の計算
total_cost = total_creation_cost + review_and_fix_cost + management_cost
# 結果を出力
print(f"全ての画面を作成する総工数は {total_cost:.1f} 人日です。")
import numpy as np
import matplotlib.pyplot as plt
# 使用量の定義
usage = np.linspace(0, 100, 500)
# 逓減課金方式の料金設定
def declining_rate_pricing(usage):
if usage <= 20:
return usage * 5 # 最初の20単位は5円/単位
elif usage <= 50:
return 20 * 5 + (usage - 20) * 4 # 次の30単位は4円/単位
elif usage <= 80:
return 20 * 5 + 30 * 4 + (usage - 50) * 3 # 次の30単位は3円/単位
else:
return 20 * 5 + 30 * 4 + 30 * 3 + (usage - 80) * 2 # それ以上は2円/単位
# 各使用量に対する料金を計算
pricing = np.array([declining_rate_pricing(u) for u in usage])
# グラフの描画
plt.figure(figsize=(10, 6))
plt.plot(usage, pricing, label="Declining Rate Pricing", color='blue')
plt.title("Declining Rate Pricing for IT Service Usage")
plt.xlabel("Usage (units)")
plt.ylabel("Price (yen)")
plt.grid(True)
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# サンプルデータ
np.random.seed(42)
n = 30
x = np.random.rand(n) * 100 # x座標
y = np.random.rand(n) * 100 # y座標
sizes = np.random.rand(n) * 1000 # バブルの大きさ(ランダムな値)
# バブルチャートの描画
plt.figure(figsize=(10, 6))
plt.scatter(x, y, s=sizes, c=x, cmap='viridis', alpha=0.6, edgecolors='w', linewidth=2)
# グラフの設定
plt.title('Bubble Chart Example')
plt.xlabel('X Axis Label')
plt.ylabel('Y Axis Label')
plt.colorbar(label='Color Scale (Based on X values)') # カラーバーを追加
plt.grid(True)
# グラフを表示
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# Parameters for the power-law distribution
total_products = 1000 # Total number of products
x = np.arange(1, total_products + 1) # Product rank from most popular to least
C = 100 # Scaling constant
alpha = 1.5 # Power-law exponent (controls how sales decline)
# Sales volume follows a power-law distribution
sales_volume = C / (x ** alpha)
# Plotting the sales distribution
plt.figure(figsize=(10, 6))
plt.plot(x, sales_volume, label='Sales Volume (Long Tail)', color='blue')
plt.xscale('log') # Logarithmic scale for product rank
plt.yscale('log') # Logarithmic scale for sales volume
plt.xlabel('Product Rank (log scale)', fontsize=12)
plt.ylabel('Sales Volume (log scale)', fontsize=12)
plt.title('Long Tail Sales Distribution', fontsize=16)
plt.legend()
plt.grid(True, which='both', linestyle='--')
# Show the plot
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# Parameters
order_interval = 10 # Order interval (e.g., order every 10 days)
order_amount = 100 # Order quantity
initial_stock = 50 # Initial stock level
daily_demand = 5 # Daily demand
# Simulation settings
days = 100 # Number of days for simulation
stock = np.zeros(days) # Array to record stock levels
stock[0] = initial_stock
# Simulation
for day in range(1, days):
# Subtract daily demand from previous day's stock
stock[day] = stock[day - 1] - daily_demand
# Place an order based on the order interval
if day % order_interval == 0:
stock[day] += order_amount
# Plot
plt.figure(figsize=(12, 6))
plt.plot(stock, marker='o', linestyle='-', color='b')
plt.title('Stock Level Variation with Periodic Ordering')
plt.xlabel('Days')
plt.ylabel('Stock Level')
plt.grid(True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# Parameters
reorder_point = 20 # Reorder point
order_amount = 100 # Order quantity
initial_stock = 50 # Initial stock level
daily_demand = 5 # Daily demand
# Simulation settings
days = 100 # Number of days for simulation
stock = np.zeros(days) # Array to record stock levels
stock[0] = initial_stock
# Simulation
for day in range(1, days):
# Subtract daily demand from previous day's stock
stock[day] = stock[day - 1] - daily_demand
# Place an order if stock falls below the reorder point
if stock[day] < reorder_point:
stock[day] += order_amount
# Plot
plt.figure(figsize=(12, 6))
plt.plot(stock, marker='o', linestyle='-', color='r')
plt.title('Stock Level Variation with Reorder Point Ordering')
plt.xlabel('Days')
plt.ylabel('Stock Level')
plt.grid(True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# Parameters
D = 10000 # Annual demand
S = 50 # Cost per order
H = 2 # Holding cost per unit per year
# EOQ Calculation
EOQ = np.sqrt((2 * D * S) / H)
# Define a range of order quantities
order_quantities = np.linspace(0, 2 * EOQ, 500)
# Calculate total cost for each order quantity
def total_cost(Q):
return (D / Q) * S + (Q / 2) * H
total_costs = total_cost(order_quantities)
# Plotting
plt.figure(figsize=(10, 6))
plt.plot(order_quantities, total_costs, label='Total Cost', color='blue')
plt.axvline(x=EOQ, color='red', linestyle='--', label='EOQ')
plt.xlabel('Order Quantity')
plt.ylabel('Total Cost')
plt.title('Total Cost vs. Order Quantity')
plt.legend()
plt.grid(True)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
# データ設定
categories = ['A', 'B', 'C', 'D', 'E']
values = [50, 30, 15, 5, 1]
# データを降順にソート
sorted_indices = np.argsort(values)[::-1]
sorted_values = np.array(values)[sorted_indices]
sorted_categories = np.array(categories)[sorted_indices]
# パレート図の作成
plt.figure(figsize=(10, 6))
plt.bar(sorted_categories, sorted_values, color='b')
plt.xlabel('Category')
plt.ylabel('Frequency')
plt.title('Pareto Chart')
plt.show()
import matplotlib.pyplot as plt
# フィッシュボーン図の作成
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot([0, 1], [0, 0], 'k', lw=2) # 主軸
ax.plot([0.5, 0.5], [0.1, -0.1], 'k', lw=2) # 魚の骨
ax.text(0.5, 0.05, 'Main Problem', fontsize=12, ha='center')
# 魚の骨の枝
branches = ['Machine', 'Method', 'Material', 'Measurement', 'Manpower', 'Environment']
for i, branch in enumerate(branches):
ax.plot([0.5, 0.4 - i*0.1], [0.0, 0.1], 'k', lw=2)
ax.text(0.4 - i*0.1, 0.1, branch, fontsize=10, ha='center')
plt.xlim(0, 1)
plt.ylim(-0.2, 0.2)
plt.axis('off')
plt.title('Fishbone Diagram')
plt.show()
import matplotlib.pyplot as plt
# データ設定
x = np.random.rand(50)
y = 2 * x + np.random.normal(0, 0.1, 50)
# 散布図の作成
plt.figure(figsize=(10, 6))
plt.scatter(x, y, color='r', label='Data Points')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Diagram')
plt.legend()
plt.grid(True)
plt.show()
import matplotlib.pyplot as plt
# データ設定
data = np.random.normal(loc=0, scale=1, size=1000)
# ヒストグラムの作成
plt.figure(figsize=(10, 6))
plt.hist(data, bins=30, color='g', edgecolor='black')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.grid(True)
plt.show()
import matplotlib.pyplot as plt
# データ設定
np.random.seed(0)
data = np.random.normal(loc=50, scale=5, size=100)
mean = np.mean(data)
std_dev = np.std(data)
# 管理図の作成
plt.figure(figsize=(12, 6))
plt.plot(data, label='Data', color='blue')
plt.axhline(mean, color='green', linestyle='--', label='Mean')
plt.axhline(mean + 3*std_dev, color='red', linestyle='--', label='Upper Control Limit')
plt.axhline(mean - 3*std_dev, color='red', linestyle='--', label='Lower Control Limit')
plt.xlabel('Sample')
plt.ylabel('Value')
plt.title('Control Chart')
plt.legend()
plt.grid(True)
plt.show()
import matplotlib.pyplot as plt
# サンプルデータ
categories = ['Defect A', 'Defect B', 'Defect C']
counts = [30, 15, 5]
# チェックシートのプロット(棒グラフとして)
plt.figure(figsize=(10, 6))
plt.bar(categories, counts, color='purple')
plt.xlabel('Defect Type')
plt.ylabel('Count')
plt.title('Check Sheet')
plt.show()
import matplotlib.pyplot as plt
# 因果関係図の作成
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot([0, 1], [0, 0], 'k', lw=2) # 主軸
ax.plot([0.5, 0.4], [0.0, 0.1], 'k', lw=2) # 主要原因
ax.plot([0.5, 0.6], [0.0, 0.1], 'k', lw=2) # 主要原因
ax.text(0.5, 0.05, 'Main Problem', fontsize=12, ha='center')
# 因果関係の枝
causes = ['Cause 1', 'Cause 2', 'Cause 3']
for i, cause in enumerate(causes):
ax.plot([0.4 + i*0.2, 0.4 + i*0.2], [0.1, 0.2], 'k', lw=2)
ax.text(0.4 + i*0.2, 0.22, cause, fontsize=10, ha='center')
plt.xlim(0, 1)
plt.ylim(-0.1, 0.3)
plt.axis('off')
plt.title('Cause and Effect Diagram')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
# データ設定(カテゴリと金額)
categories = ['Item A', 'Item B', 'Item C', 'Item D', 'Item E']
amounts = [1000, 700, 300, 200, 100]
# データを降順にソート
sorted_indices = np.argsort(amounts)[::-1]
sorted_amounts = np.array(amounts)[sorted_indices]
sorted_categories = np.array(categories)[sorted_indices]
# 累積パーセンテージの計算
cumulative_amounts = np.cumsum(sorted_amounts)
total_amount = cumulative_amounts[-1]
cumulative_percentage = cumulative_amounts / total_amount * 100
# パレート図の作成
fig, ax1 = plt.subplots(figsize=(10, 6))
# バーグラフ(各カテゴリの金額)
color = 'tab:blue'
ax1.set_xlabel('Category')
ax1.set_ylabel('Amount', color=color)
ax1.bar(sorted_categories, sorted_amounts, color=color)
ax1.tick_params(axis='y', labelcolor=color)
# 折れ線グラフ(累積パーセンテージ)
ax2 = ax1.twinx()
color = 'tab:red'
ax2.set_ylabel('Cumulative Percentage (%)', color=color)
ax2.plot(sorted_categories, cumulative_percentage, color=color, marker='o', linestyle='--')
ax2.tick_params(axis='y', labelcolor=color)
# タイトルとレイアウト
plt.title('Pareto Chart')
fig.tight_layout()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# パラメータ設定
n = 100 # サンプルサイズ
c = 2 # 許容できる不良品数
# 不良率の範囲
p = np.linspace(0, 0.2, 100)
# 合格率の計算
def oc_curve(p, n, c):
return 1 - (1 - p)**n
# OC曲線の計算
pass_rates = [1 - sum(np.math.comb(n, k) * (p_i**k) * ((1 - p_i)**(n - k)) for k in range(c + 1)) for p_i in p]
# プロット
plt.figure(figsize=(10, 6))
plt.plot(p, pass_rates, label='OC Curve', color='blue')
plt.xlabel('Lot Defect Rate (p)')
plt.ylabel('Probability of Passing the Lot')
plt.title('Operating Characteristic (OC) Curve')
plt.grid(True)
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# パラメータ設定
initial_cost = 10000 # 資産の取得原価
depreciation_rate = 0.2 # 減価償却率(例: 20%)
useful_life_years = 10 # 資産の耐用年数
# 初期化
book_value = initial_cost
depreciation_expenses = []
book_values = []
# 各年の減価償却費と簿価の計算
for year in range(useful_life_years):
depreciation_expense = book_value * depreciation_rate
depreciation_expenses.append(depreciation_expense)
book_value -= depreciation_expense
book_values.append(book_value)
# プロット
years = np.arange(1, useful_life_years + 1)
plt.figure(figsize=(10, 6))
plt.plot(years, book_values, marker='o', label='Book Value', color='blue')
plt.xlabel('Year')
plt.ylabel('Book Value')
plt.title('Declining Balance Method Depreciation')
plt.grid(True)
plt.legend()
plt.show()
import numpy as np
# CPU性能メトリクス
def calculate_mips(instruction_execution_time):
return 1 / (instruction_execution_time * 1e-6) # nMIPS
def average_instruction_execution_time(mips):
return 1 / (mips * 1e6) # 秒
def clock_cycle_time(clock_frequency_mhz):
return 1 / (clock_frequency_mhz * 1e6) # 秒
def average_instruction_execution_time_from_clock(clock_cycle_time, cycles_per_instruction):
return clock_cycle_time * cycles_per_instruction # 秒
# メモリアクセス時間
def cache_memory_access_time(hit_rate, cache_access_time):
return hit_rate * cache_access_time
def main_memory_access_time(miss_rate, main_memory_access_time):
return miss_rate * main_memory_access_time
def cpu_effective_access_time(cache_access_time, main_memory_access_time):
return cache_access_time + main_memory_access_time
# VRAMと画像データ容量
def required_vram_capacity(total_pixels, color_info_bits):
return total_pixels * color_info_bits # ビット
def image_data_capacity(total_pixels, color_info_bits):
return total_pixels * color_info_bits # ビット
# 電力とバッテリー容量
def power_consumption(voltage, current):
return voltage * current # ワット
def battery_capacity(current, time_hours):
return current * time_hours # アンペア・アワー
# サンプルデータ
instruction_execution_time = 2e-8 # 秒
mips = calculate_mips(instruction_execution_time)
print(f"MIPS: {mips:.2f} million instructions per second")
clock_frequency_mhz = 3000 # MHz
cycles_per_instruction = 4
cycle_time = clock_cycle_time(clock_frequency_mhz)
avg_instr_exec_time = average_instruction_execution_time_from_clock(cycle_time, cycles_per_instruction)
print(f"Average Instruction Execution Time: {avg_instr_exec_time:.2e} seconds")
hit_rate = 0.95
cache_access_time = 1e-6 # 秒
main_memory_access_time_val = 10e-6 # 秒
cache_avg_time = cache_memory_access_time(hit_rate, cache_access_time)
main_memory_avg_time = main_memory_access_time(1 - hit_rate, main_memory_access_time_val)
effective_access_time = cpu_effective_access_time(cache_avg_time, main_memory_avg_time)
print(f"CPU Effective Access Time: {effective_access_time:.2e} seconds")
total_pixels = 1920 * 1080 # 画面解像度
color_info_bits = 24 # 24ビットカラー
vram_capacity = required_vram_capacity(total_pixels, color_info_bits)
image_capacity = image_data_capacity(total_pixels, color_info_bits)
print(f"Required VRAM Capacity: {vram_capacity / 8 / 1e6:.2f} MB")
print(f"Image Data Capacity: {image_capacity / 8 / 1e6:.2f} MB")
voltage = 5 # ボルト
current = 2 # アンペア
power = power_consumption(voltage, current)
print(f"Power Consumption: {power:.2f} W")
battery_current = 2 # アンペア
battery_time_hours = 5 # 時間
battery_capacity_val = battery_capacity(battery_current, battery_time_hours)
print(f"Battery Capacity: {battery_capacity_val:.2f} Ah")
def calculate_data_transmission_time(data_amount_bits, transmission_speed_bps, line_utilization):
"""
Calculate the data transmission time.
Parameters:
data_amount_bits (int): Amount of data to be transmitted in bits.
transmission_speed_bps (int): Data transmission speed in bits per second.
line_utilization (float): Line utilization (between 0 and 1).
Returns:
float: Data transmission time in seconds.
"""
return data_amount_bits / (transmission_speed_bps * line_utilization)
def calculate_line_utilization(effective_transmission_speed_bps, max_transmission_speed_bps):
"""
Calculate the line utilization.
Parameters:
effective_transmission_speed_bps (int): Effective transmission speed in bits per second.
max_transmission_speed_bps (int): Maximum possible transmission speed in bits per second.
Returns:
float: Line utilization (between 0 and 1).
"""
return effective_transmission_speed_bps / max_transmission_speed_bps
# サンプルデータ
data_amount_bits = 50000000 # 伝送データ量 (ビット)
transmission_speed_bps = 100000000 # データ伝送速度 (ビット/秒)
effective_transmission_speed_bps = 75000000 # 実効伝送速度 (ビット/秒)
# 回線利用率の計算
line_utilization = calculate_line_utilization(effective_transmission_speed_bps, transmission_speed_bps)
print(f"Line Utilization: {line_utilization:.2f}")
# データ伝送時間の計算
transmission_time = calculate_data_transmission_time(data_amount_bits, transmission_speed_bps, line_utilization)
print(f"Data Transmission Time: {transmission_time:.2f} seconds")
import numpy as np
import matplotlib.pyplot as plt
def calculate_break_even_sales(fixed_costs, variable_costs_ratio):
"""
Calculate the break-even sales revenue.
Parameters:
fixed_costs (float): Fixed costs.
variable_costs_ratio (float): Variable costs ratio (0 to 1).
Returns:
float: Break-even sales revenue.
"""
return fixed_costs / (1 - variable_costs_ratio)
def calculate_variable_costs_ratio(variable_costs, sales_revenue):
"""
Calculate the variable costs ratio.
Parameters:
variable_costs (float): Variable costs.
sales_revenue (float): Sales revenue.
Returns:
float: Variable costs ratio (0 to 1).
"""
return variable_costs / sales_revenue
# サンプルデータ
fixed_costs = 50000 # 固定費
variable_costs = 30000 # 変動費
sales_revenue = 100000 # 売上高
# 変動費率の計算
variable_costs_ratio = calculate_variable_costs_ratio(variable_costs, sales_revenue)
print(f"Variable Costs Ratio: {variable_costs_ratio:.2f}")
# 損益分岐点売上高の計算
break_even_sales = calculate_break_even_sales(fixed_costs, variable_costs_ratio)
print(f"Break-even Sales Revenue: ${break_even_sales:.2f}")
# プロット
sales_range = np.linspace(0, 2 * sales_revenue, 100)
profit_or_loss = sales_range - (fixed_costs + variable_costs_ratio * sales_range)
plt.figure(figsize=(10, 6))
plt.plot(sales_range, profit_or_loss, label='Profit or Loss', color='blue')
plt.axhline(0, color='red', linestyle='--', label='Break-even Point')
plt.xlabel('Sales Revenue ($)')
plt.ylabel('Profit or Loss ($)')
plt.title('Break-even Analysis')
plt.legend()
plt.grid(True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
def calculate_maximum_profit(selling_price, variable_cost, expected_demand, fixed_costs):
"""
Calculate the maximum profit.
Parameters:
selling_price (float): Selling price per unit.
variable_cost (float): Variable cost per unit.
expected_demand (float): Expected demand.
fixed_costs (float): Fixed costs.
Returns:
float: Maximum profit.
"""
return (selling_price - variable_cost) * expected_demand - fixed_costs
def calculate_expected_demand(selling_price, price_demand_intercept, price_demand_slope):
"""
Calculate the expected demand based on the selling price.
Parameters:
selling_price (float): Selling price per unit.
price_demand_intercept (float): Intercept of the price-demand line.
price_demand_slope (float): Slope of the price-demand line.
Returns:
float: Expected demand.
"""
return price_demand_intercept - price_demand_slope * selling_price
def calculate_expected_profit(selling_price, price_demand_intercept, price_demand_slope, variable_cost, fixed_costs):
"""
Calculate the expected profit.
Parameters:
selling_price (float): Selling price per unit.
price_demand_intercept (float): Intercept of the price-demand line.
price_demand_slope (float): Slope of the price-demand line.
variable_cost (float): Variable cost per unit.
fixed_costs (float): Fixed costs.
Returns:
float: Expected profit.
"""
expected_demand = calculate_expected_demand(selling_price, price_demand_intercept, price_demand_slope)
return (selling_price - variable_cost) * expected_demand - fixed_costs
# サンプルデータ
selling_price = 120 # 設定価格
variable_cost = 60 # 変動費
expected_demand = 500 # 予想需要数
fixed_costs = 10000 # 固定費
# 最大利益の計算
max_profit = calculate_maximum_profit(selling_price, variable_cost, expected_demand, fixed_costs)
print(f"Maximum Profit: ${max_profit:.2f}")
# 期待利益の計算
price_demand_intercept = 1000 # 価格-需要線の切片
price_demand_slope = 5 # 価格-需要線の傾き
# 価格の範囲
price_range = np.linspace(50, 150, 100)
expected_profits = [calculate_expected_profit(price, price_demand_intercept, price_demand_slope, variable_cost, fixed_costs) for price in price_range]
# プロット
plt.figure(figsize=(10, 6))
plt.plot(price_range, expected_profits, label='Expected Profit', color='green')
plt.xlabel('Selling Price ($)')
plt.ylabel('Expected Profit ($)')
plt.title('Expected Profit vs Selling Price')
plt.axhline(0, color='red', linestyle='--', label='Break-even Point')
plt.legend()
plt.grid(True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
def reliability_series(reliabilities):
"""
Calculate the reliability of a series system.
Parameters:
reliabilities (list of float): Reliability of each component in series.
Returns:
float: Reliability of the series system.
"""
return np.prod(reliabilities)
def reliability_parallel(reliabilities):
"""
Calculate the reliability of a parallel system.
Parameters:
reliabilities (list of float): Reliability of each component in parallel.
Returns:
float: Reliability of the parallel system.
"""
return 1 - np.prod(1 - np.array(reliabilities))
# サンプルデータ
reliabilities = [0.9, 0.8, 0.7] # 各コンポーネントの信頼性
# 直列システムの信頼性の計算
series_reliability = reliability_series(reliabilities)
print(f"Series System Reliability: {series_reliability:.2f}")
# 並列システムの信頼性の計算
parallel_reliability = reliability_parallel(reliabilities)
print(f"Parallel System Reliability: {parallel_reliability:.2f}")
# プロットの準備
reliability_range = np.linspace(0.1, 0.9, 100)
series_reliabilities = [reliability_series([r] * 3) for r in reliability_range]
parallel_reliabilities = [reliability_parallel([r] * 3) for r in reliability_range]
# プロット
plt.figure(figsize=(12, 6))
plt.plot(reliability_range, series_reliabilities, label='Series System Reliability', color='blue')
plt.plot(reliability_range, parallel_reliabilities, label='Parallel System Reliability', color='green')
plt.xlabel('Component Reliability')
plt.ylabel('System Reliability')
plt.title('System Reliability vs Component Reliability')
plt.legend()
plt.grid(True)
plt.show()
import networkx as nx
import matplotlib.pyplot as plt
def draw_tree():
# Create a new directed graph
G = nx.DiGraph()
# Define the edges of the tree (parent, child)
edges = [
('Root', 'Child 1'),
('Root', 'Child 2'),
('Child 1', 'Grandchild 1.1'),
('Child 1', 'Grandchild 1.2'),
('Child 2', 'Grandchild 2.1'),
('Child 2', 'Grandchild 2.2'),
('Grandchild 1.2', 'Great-Grandchild 1.2.1')
]
# Add edges to the graph
G.add_edges_from(edges)
# Create a layout for the nodes (tree layout)
pos = nx.spring_layout(G, seed=42) # Use spring layout for better visualization
# Draw the nodes and edges
plt.figure(figsize=(10, 7))
nx.draw(G, pos, with_labels=True, node_size=2000, node_color='skyblue', font_size=12, font_weight='bold', edge_color='gray')
# Set the title
plt.title('Tree Structure')
# Show the plot
plt.show()
# Call the function to draw the tree
draw_tree()
import numpy as np
import matplotlib.pyplot as plt
# Parameters
A_c = 1.0 # Carrier amplitude
A_m = 0.5 # Modulating signal amplitude
f_c = 5.0 # Carrier frequency (Hz)
f_m = 1.0 # Modulating frequency (Hz)
k_f = 1.0 # Frequency modulation sensitivity
k_p = np.pi # Phase modulation sensitivity
t = np.linspace(0, 1, 1000) # Time vector
# Modulating signal
m = A_m * np.sin(2 * np.pi * f_m * t)
# Amplitude Modulated Signal (AM)
s_am = (A_c + m) * np.cos(2 * np.pi * f_c * t)
# Frequency Modulated Signal (FM)
s_fm = A_c * np.cos(2 * np.pi * f_c * t + 2 * np.pi * k_f * np.cumsum(m) / 1000)
# Phase Modulated Signal (PM)
s_pm = A_c * np.cos(2 * np.pi * f_c * t + k_p * m)
# Quadrature Amplitude Modulated Signal (QAM)
A1 = A_m * np.cos(2 * np.pi * f_m * t)
A2 = A_m * np.sin(2 * np.pi * f_m * t)
s_qam = A1 * np.cos(2 * np.pi * f_c * t) + A2 * np.sin(2 * np.pi * f_c * t)
# Phase Shift Keying (PSK)
phi = np.pi * np.sin(2 * np.pi * f_m * t) # Example phase shift
s_psk = A_c * np.cos(2 * np.pi * f_c * t + phi)
# Plotting
plt.figure(figsize=(14, 12))
# AM Signal
plt.subplot(5, 1, 1)
plt.plot(t, m, label='Modulating Signal')
plt.title('Modulating Signal')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.grid(True)
plt.subplot(5, 1, 2)
plt.plot(t, s_am, label='AM Signal', color='orange')
plt.title('Amplitude Modulated Signal (AM)')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.grid(True)
# FM Signal
plt.subplot(5, 1, 3)
plt.plot(t, s_fm, label='FM Signal', color='green')
plt.title('Frequency Modulated Signal (FM)')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.grid(True)
# PM Signal
plt.subplot(5, 1, 4)
plt.plot(t, s_pm, label='PM Signal', color='blue')
plt.title('Phase Modulated Signal (PM)')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.grid(True)
# QAM Signal
plt.subplot(5, 1, 5)
plt.plot(t, s_qam, label='QAM Signal', color='red')
plt.title('Quadrature Amplitude Modulated Signal (QAM)')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.grid(True)
plt.tight_layout()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# Parameters
t = np.linspace(0, 100, 1000) # Time vector
initial_failure_rate = 0.2 # Initial failure rate (decreasing)
normal_failure_rate = 0.05 # Normal period failure rate
wearout_failure_rate = 0.1 # Wear-out period failure rate (increasing)
transition_point1 = 20 # Time when transition from initial to normal period occurs
transition_point2 = 70 # Time when transition from normal to wear-out period occurs
# Bathtub Curve
def bathtub_curve(t, initial_failure_rate, normal_failure_rate, wearout_failure_rate, transition_point1, transition_point2):
failure_rate = np.zeros_like(t)
# Initial failure period
failure_rate[t < transition_point1] = initial_failure_rate * (1 - (t[t < transition_point1] / transition_point1))
# Normal period
failure_rate[(t >= transition_point1) & (t < transition_point2)] = normal_failure_rate
# Wear-out period
failure_rate[t >= transition_point2] = wearout_failure_rate * ((t[t >= transition_point2] - transition_point2) / (100 - transition_point2))
return failure_rate
# Compute the failure rate
failure_rate = bathtub_curve(t, initial_failure_rate, normal_failure_rate, wearout_failure_rate, transition_point1, transition_point2)
# Plotting
plt.figure(figsize=(10, 6))
plt.plot(t, failure_rate, label='Bathtub Curve', color='purple')
plt.title('Bathtub Curve')
plt.xlabel('Time')
plt.ylabel('Failure Rate')
plt.grid(True)
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# Parameters
t = np.linspace(0, 100, 1000) # Time vector
uptime_initial = 10 # Initial uptime (constant)
downtime_initial = 5 # Initial downtime (constant)
uptime_normal = 95 # Normal uptime rate (constant)
downtime_normal = 5 # Normal downtime rate (constant)
uptime_wearout = 90 # Wear-out uptime rate (decreasing)
downtime_wearout = 10 # Wear-out downtime rate (increasing)
transition_point1 = 20 # Time when transition from initial to normal period occurs
transition_point2 = 70 # Time when transition from normal to wear-out period occurs
# Uptime and Downtime Calculation
def uptime_downtime(t, uptime_initial, downtime_initial, uptime_normal, downtime_normal, uptime_wearout, downtime_wearout, transition_point1, transition_point2):
uptime = np.zeros_like(t)
downtime = np.zeros_like(t)
# Initial phase
uptime[t < transition_point1] = uptime_initial * (t[t < transition_point1] / transition_point1)
downtime[t < transition_point1] = downtime_initial * (t[t < transition_point1] / transition_point1)
# Normal phase
uptime[(t >= transition_point1) & (t < transition_point2)] = uptime_normal * (t[(t >= transition_point1) & (t < transition_point2)] - transition_point1) + uptime_initial
downtime[(t >= transition_point1) & (t < transition_point2)] = downtime_normal * (t[(t >= transition_point1) & (t < transition_point2)] - transition_point1) + downtime_initial
# Wear-out phase
uptime[t >= transition_point2] = uptime_wearout * ((t[t >= transition_point2] - transition_point2) / (100 - transition_point2)) + uptime_normal
downtime[t >= transition_point2] = downtime_wearout * ((t[t >= transition_point2] - transition_point2) / (100 - transition_point2)) + downtime_normal
return uptime, downtime
# Compute uptime and downtime
uptime, downtime = uptime_downtime(t, uptime_initial, downtime_initial, uptime_normal, downtime_normal, uptime_wearout, downtime_wearout, transition_point1, transition_point2)
# Compute Availability
availability = uptime / (uptime + downtime)
# Plotting
plt.figure(figsize=(12, 6))
plt.subplot(3, 1, 1)
plt.plot(t, uptime, label='Uptime', color='green')
plt.title('System Uptime')
plt.xlabel('Time')
plt.ylabel('Uptime')
plt.grid(True)
plt.subplot(3, 1, 2)
plt.plot(t, downtime, label='Downtime', color='red')
plt.title('System Downtime')
plt.xlabel('Time')
plt.ylabel('Downtime')
plt.grid(True)
plt.subplot(3, 1, 3)
plt.plot(t, availability, label='Availability', color='blue')
plt.title('System Availability')
plt.xlabel('Time')
plt.ylabel('Availability')
plt.grid(True)
plt.tight_layout()
plt.show()
import psutil
import matplotlib.pyplot as plt
import time
# 設定
duration = 10 # 監視する時間(秒)
interval = 1 # サンプリング間隔(秒)
# メモリ使用量を記録するリスト
times = []
memories = []
# 開始時間
start_time = time.time()
# メモリ使用量を監視
while time.time() - start_time < duration:
times.append(time.time() - start_time)
memory_info = psutil.virtual_memory()
memories.append(memory_info.percent)
time.sleep(interval)
# プロット
plt.figure(figsize=(10, 5))
plt.plot(times, memories, label='Memory Usage (%)')
plt.xlabel('Time (s)')
plt.ylabel('Memory Usage (%)')
plt.title('Memory Usage Over Time')
plt.grid(True)
plt.legend()
plt.show()