CPI(Consumer Price Index)是衡量消费者物价水平的指数。它通过统计一定时期内消费者购买的商品和服务的价格变化情况来反映物价水平的变化。CPI通常根据不同品类的商品和服务分别计算,然后再按一定权重加总得到综合指数。
下面是一个简单的Java代码示例,用于计算CPI多品类指数模型:
import java.util.HashMap;
import java.util.Map;
public class CPICalculator {
// 不同品类的商品和服务
private Map<String, Double> items = new HashMap<>();
// 不同品类商品和服务在总消费中所占比例
private Map<String, Double> weights = new HashMap<>();
/**
* 添加一个品类及其对应的商品和服务及其权重
*
* @param category 品类名称
* @param items 商品和服务及其价格
* @param weight 权重
*/
public void addCategory(String category, Map<String, Double> items, double weight) {
this.items.putAll(items);
this.weights.put(category, weight);
}
/**
* 计算CPI指数
*
* @return CPI指数
*/
public double calculate() {
double sum = 0;
for (String category : weights.keySet()) {
double weight = weights.get(category);
double subtotal = 0;
for (String item : items.keySet()) {
if (item.startsWith(category)) {
subtotal += items.get(item);
}
}
sum += subtotal * weight;
}
return sum;
}
/**
* 测试代码
*/
public static void main(String[] args) {
CPICalculator calculator = new CPICalculator();
Map<String, Double> foodItems = new HashMap<>();
foodItems.put("rice", 10.0);
foodItems.put("vegetables", 20.0);
foodItems.put("meat", 30.0);
calculator.addCategory("food", foodItems, 0.5);
Map<String, Double> housingItems = new HashMap<>();
housingItems.put("rent", 100.0);
housingItems.put("utilities", 50.0);
calculator.addCategory("housing", housingItems, 0.3);
Map<String, Double> transportationItems = new HashMap<>();
transportationItems.put("gasoline", 40.0);
transportationItems.put("car maintenance", 20.0);
calculator.addCategory("transportation", transportationItems, 0.2);
double cpi = calculator.calculate();
System.out.println("CPI: " + cpi);
}