1104. Sum of Number Segments 解析

本文探讨了使用特定三角形结构进行数值计算的方法,并通过示例展示了计算过程。作者使用了一个具体的C++程序来实现计算,同时表达了对于计算精度的关注,并提到了可能会遇到的问题。

我按三角形来计算的时候例如

0.1

0.1  0.2 

0.1  0.2  0.3

0.1  0.2  0.3  0.4、

0.2 

0.2  0.3

0.2  0.3  0.4

0.3

0.3   0.4

0.4

估计计算的精度会出现问题。会有一个不能AC/

按照大神们的计算方法可以AC。。到时候再查查什么地方出了问题。


#include <iostream>

#define MAX 100010

using namespace std;

int n;

int main() {
	cin >> n;
	double temp,sum = 0;
	for (int i = 1; i <= n; i++) {
		scanf("%lf", &temp);
		sum += temp * i * (n - i + 1);
	}

	printf("%.2lf\n", sum);

	return 0;
}


import numpy as np import bisect import matplotlib.pyplot as plt # 定义 Silu 函数 def silu(x): return x / (1 + np.exp(-x)) # 分段参数 N_SEGMENTS = 1024 + 1 # 增加分段数(原为512+1) X_MIN, X_MAX = -8.0, 8.0 # 扩展定义域(原为[-4,4]) DX = (X_MAX - X_MIN) / (N_SEGMENTS - 1) class SiluLUT: def __init__(self, is_sys=False): if is_sys: self.coeffs, self.seg = self.calculate_symmetric_coeffs() else: self.coeffs, self.seg = self.calculate_coefficients() self.x_min = X_MIN self.x_max = X_MAX self.dx = DX def func_silu(self, a, b, c, x): return a * x**2 + b * x + c # 二次多项式近似 def __call__(self, x): # 处理边界外的输入 x = np.clip(x, self.x_min + 1e-6, self.x_max - 1e-6) # 避免边界溢出 # 计算分段索引 idx = np.clip(int((x - self.x_min) / self.dx), 0, N_SEGMENTS - 2) # 获取系数 a, b, c = self.coeffs[idx] return self.func_silu(a, b, c, x) def calculate_coefficients(self): coefficients = np.zeros((N_SEGMENTS - 1, 3)) # 每个分段存储[a, b, c] seg = [] for i in range(N_SEGMENTS - 1): start = X_MIN + i * DX end = start + DX seg.append([start, end]) # 增加采样点数量(原为20个) x_samples = np.linspace(start, end, 100) # 100个采样点 y_samples = silu(x_samples) # 改进拟合方法:加权最小二乘,中间点权重更高 # 定义左侧加权函数(指数衰减) # tau = 2.0 # weights = np.exp(-x_samples / tau) # weights = weights / np.sum(weights) weights = np.exp(-0.5 * ((x_samples - (start + end)/2) / (DX/4))**2) # 高斯权重 A = np.vstack([x_samples**2, x_samples, np.ones_like(x_samples)]).T coef, _, _, _ = np.linalg.lstsq(A * weights[:, np.newaxis], y_samples * weights, rcond=None) coefficients[i] = coef return coefficients, seg def evaluate_accuracy(lut, n_samples=100000): x_test = np.linspace(X_MIN, X_MAX, n_samples) y_true = silu(x_test) y_pred = np.array([lut(x) for x in x_test]) # 计算误差 abs_error = np.abs(y_true - y_pred) max_error = np.max(abs_error) rmse = np.sqrt(np.mean(abs_error**2)) # 统计超出门限的误差 threshold = 1e-5 # 更严格的门限(原为1e-4) over_threshold = np.sum(abs_error > threshold) / n_samples # 绘制误差分布 plt.figure(figsize=(12, 6)) plt.scatter(x_test, abs_error, s=1, alpha=0.5) plt.axhline(threshold, color='r', linestyle='--', label='Threshold') plt.title('Absolute Error Distribution') plt.xlabel('Input Value') plt.ylabel('Absolute Error') plt.yscale('log') # 对数坐标更清晰 plt.grid(True) plt.legend() plt.savefig('error_distribution_optimized.png') plt.close() # 绘制函数对比(高分辨率) plt.figure(figsize=(12, 6)) plt.plot(x_test, y_true, label='True Silu', linewidth=0.5) plt.plot(x_test, y_pred, label='LUT Approximation', linewidth=0.5) plt.title('Silu Function vs. LUT Approximation') plt.xlabel('Input') plt.ylabel('Output') plt.legend() plt.grid(True) plt.savefig('function_comparison_optimized.png') plt.close() return max_error, rmse, over_threshold # 测试优化后的实现 optimized_lut = SiluLUT() max_err, rmse, over_th = evaluate_accuracy(optimized_lut) print(f"优化实现: MaxError={max_err:.2e}, RMSE={rmse:.2e}, >1e-5比例={over_th*100:.4f}%") 我就想用多项式泰勒级数展开,能否帮我优化好
12-12
D:\anaconda3\python.exe E:\exercise\curve_fund\project5\pythonProject\006.py 开始反演挠度场... 执行全局优化... 全局优化失败: Bounds are not consistent min < max 回退到初始猜测... 执行局部优化... RUNNING THE L-BFGS-B CODE * * * Machine precision = 2.220D-16 N = 49 M = 10 At X0 0 variables are exactly at the bounds At iterate 0 f= 2.02630D+03 |proj g|= 1.80000D-05 At iterate 1 f= 1.10167D+02 |proj g|= 3.20000D-05 At iterate 2 f= 2.98516D-02 |proj g|= 3.16141D-05 At iterate 3 f= 2.95950D-02 |proj g|= 3.16124D-05 At iterate 4 f= 2.82784D-02 |proj g|= 3.37033D-06 * * * Tit = total number of iterations Tnf = total number of function evaluations Tnint = total number of segments explored during Cauchy searches Skip = number of BFGS updates skipped Nact = number of active bounds at final generalized Cauchy point Projg = norm of the final projected gradient F = final function value * * * N Tit Tnf Tnint Skip Nact Projg F 49 4 6 52 0 0 3.370D-06 2.828D-02 F = 2.827841160460517E-002 CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL 局部优化完成, 目标函数值: 2.8278e-02 ================================================== 优化耗时: 1.14秒 位移反演相对误差: 98.10% 应变反演相对测量值误差: 855689.05% ================================================== Traceback (most recent call last): File "E:\exercise\curve_fund\project5\pythonProject\006.py", line 307, in <module> plot_results(v_inv, eps_recovered) File "E:\exercise\curve_fund\project5\pythonProject\006.py", line 279, in plot_results plt.pcolormesh(X, Z, strain_error.T, shading='auto', cmap='hot_r') File "D:\anaconda3\Lib\site-packages\matplotlib\pyplot.py", line 3697, in pcolormesh __ret = gca().pcolormesh( ^^^^^^^^^^^^^^^^^ File "D:\anaconda3\Lib\site-packages\matplotlib\__init__.py", line 1473, in inner return func( ^^^^^ File "D:\anaconda3\Lib\site-packages\matplotlib\axes\_axes.py", line 6428, in pcolormesh X, Y, C, shading = self._pcolorargs('pcolormesh', *args, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\anaconda3\Lib\site-packages\matplotlib\axes\_axes.py", line 5975, in _pcolorargs raise TypeError(f"Dimensions of C {C.shape} should" TypeError: Dimensions of C (5, 50) should be one smaller than X(5) and Y(50) while using shading='flat' see help(pcolormesh) 进程已结束,退出代码为 1
最新发布
12-13
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值