java - 基本二项式期权定价模型
问题描述
我尝试在 Java 中创建二项式期权定价模型树,但无法想出制作内部树的方法。
到目前为止,我拥有的代码是这个
double[][] Price = new double[4][4];
for (int i = 0; i < Price.length; i++) {
Price[0][i] = Math.pow(m.U(), i);
Price[i][0] = Math.pow(m.D(), i);
System.out.println("u^" + i + ":" + Price[0][i]);
System.out.println("d^" + i + ":" + Price[i][0]);
}
这仅输出向上和向下分支,但我想要所有内部树分支,具体取决于存在的节点。
解决方案
我认为要走的路是在自定义树结构上使用递归。
我将使用的结构类似于此处描述的结构,但作为二叉树(只有两个孩子)。例子 :
public class BinTree {
private float data;
private BinTree left; //left Sub-Tree
private BinTree right; //right Sub-Tree
/* creation of the tree */
public Tree(float rootData) {
data = rootData;
/* left and right are NULL, which means that
there is no left child and no right child */
}
public addLeft(float data) {
left = new BinTree(data);
/* You can verify first if there's a child,
and maybe give an exception if there is */
}
public addRight(T data) {
right = new BinTree(data);
/* You can verify first if there's a child,
and maybe give an exception if there is */
}
/* methods like your algorithm */
...
}
您可以替换float
为任何类型
使用这种结构,递归变得非常容易。
而要递归处理这个问题,你需要想象一下:你在一个节点上,你需要在这个节点上做什么?你需要在孩子身上涂抹一些东西吗?如果是,您如何使用相同的功能来获得预期的输出?
从我看到的你的照片来看,有3种情况:
1 - 当前节点的值为So
然后,你的孩子 left 应该得到 valueSo * u
而你的孩子 right 应该得到 value So * d
。
2 - 当前节点的值为So * nd
, 为n
整数
然后,你的孩子左边应该得到价值So * (n-1)d
(并且只是So
如果n = 1
),你的孩子右边应该得到价值So * (n+1)d
。
3 - 当前节点的值为So * nu
, 为n
整数
然后,你的孩子 left 应该得到 valueSo * (n+1)u
而你的孩子 right 应该得到 value So * (n-1)u
。
所以(方法的)实现应该是这样的:
public myAlgo(float s /*So*/, T/*the type of your variable m*/ m, int height) {
myAlgo_rec(s, m, height, 0);
}
private myAlgo_rec(float s, T m, int height, int occurU) {
/* occurU is equivalent to n, and indicates if we use U or D depending on the sign */
if (height == 0) return; // Stop condition
if (occurU = 0) {
left = new BinTree(s * m.U);
right = new BinTree(s * m.D);
myAlgo_rec(s, m, height-1, 1);
myAlgo_rec(s, m, height-1, -1);
} else if (occurU < 0) {
left = new BinTree(s * Math.pow(m.U(), -occurU+1));
right = new BinTree(s * Math.pow(m.U(), -occurU-1));
myAlgo_rec(s, m, height-1, occurU+1);
myAlgo_rec(s, m, height-1, occurU-1);
} else /*occurU > 0*/ {
left = new BinTree(s * Math.pow(m.D(), occurU+1));
right = new BinTree(s * Math.pow(m.D(), occurU-1));
myAlgo_rec(s, m, height-1, occurU+1);
myAlgo_rec(s, m, height-1, occurU-1);
}
}
这里是。通常,我认为如果您理解我所说的一切,您应该能够实现它或使用我的代码(并调试它)。
推荐阅读
- docker - 尝试通过 docker-compose 为 mariadb 运行迁移时出错
- amazon-web-services - 为什么组织是有益的?
- bash - SSH 和 CI 执行命令
- bash - 尝试始终从终端记录我的命令输出,但脚本命令正在循环
- r - 如何在动物园或 xts 上使用 na.fill 使用 maxgap?
- ansible - 如何以 yaml 格式殖民 Ansible 库存
- java - 解密已经加密的字符串
- selenium - 从 docker-compose.yml 运行 Zalenium 时自动拉取相关映像
- c - 崩溃程序不生成核心转储
- javascript - DataTable 中隐藏的可搜索数据