如何在jupyter notebook中编程实现资产折旧的自定义函数,并根据调用判断函数编写是否正确。要求:分别定义三个函数(直线折旧法、双倍余额递减法、年数总和法)并进行调用
时间: 2024-09-18 09:02:24 浏览: 129
在Jupyter Notebook中实现资产折旧的自定义函数,首先需要导入必要的数学库,如`numpy`,然后我们可以定义三个不同的折旧计算函数,每个函数对应一种常见的折旧方法:
1. 直线折旧法( Straight-Line Depreciation):
```python
import numpy as np
def straight_line_depreciation(cost, useful_life, salvage_value):
"""计算直线折旧法"""
depreciation_per_period = (cost - salvage_value) / useful_life
return depreciation_per_period
```
2. 双倍余额递减法(Double Declining Balance Depreciation):
```python
def double_dbd(cost, useful_life, salvage_value):
"""计算双倍余额递减法"""
annual_rate = 2 / useful_life
balance = cost
for _ in range(useful_life):
depreciation = balance * annual_rate
yield depreciation
balance -= depreciation
yield salvage_value
```
3. 年数总和法(Sum of Years' Digits Depreciation):
```python
def syd(cost, useful_life, salvage_value):
"""计算年数总和法"""
digits_sum = sum(range(1, useful_life + 1))
rate = (useful_life - 1) / digits_sum
accumulated_depreciation = 0
for i in range(1, useful_life + 1):
this_year_depreciation = (cost - accumulated_depreciation) * rate
accumulated_depreciation += this_year_depreciation
yield this_year_depreciation
yield salvage_value
```
为了检查函数的调用是否正确,你可以提供一些示例输入,并打印出结果,比较它们是否符合预期的折旧值。例如:
```python
# 示例数据
cost = 10000
salvage_value = 2000
useful_lives = [5, 7, 10] # 对于每种方法,设定不同的使用年限
# 调用函数并检查结果
for method_name, function in {'Straight Line': straight_line_depreciation,
'Double Declining Balance': double_dbd,
'Sum of Years\' Digits': syd}.items():
for life in useful_lifes:
result = function(cost, life, salvage_value)
if isinstance(result, tuple): # 如果是生成器,需要迭代得到所有值
print(f"{method_name} with {life} years: ", list(result))
else:
print(f"{method_name} with {life} years: ", result)
```
阅读全文