get 新技能 Math.ceil();函数的用法

a=Math.ceil(a/60);//Math.ceil 返回值是一个小数 意思是返回一个大于等于它的正整数

下面Java算法还是没铺满,优化下面算法,是的水印才能铺满 private static void addWatermarkToPage(PDDocument doc, PDPage page, PDType0Font font) { try (PDPageContentStream stream = new PDPageContentStream( doc, page, PDPageContentStream.AppendMode.APPEND, true, true)) { // 获取页面尺寸 PDRectangle pageSize = page.getMediaBox(); float pageWidth = pageSize.getWidth(); float pageHeight = pageSize.getHeight(); // 设置水印样式 stream.setFont(font, FONT_SIZE); stream.setNonStrokingColor(GRAY_R, GRAY_G, GRAY_B, OPACITY); // 计算文本尺寸(核心优化) float textWidth = font.getStringWidth(WATERMARK_TEXT) * FONT_SIZE / 1000; float textHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * FONT_SIZE / 1000; // 计算旋转后实际占位尺寸 double rads = Math.toRadians(ROTATION_ANGLE); float rotatedWidth = (float) (Math.abs(textWidth * Math.cos(rads)) + Math.abs(textHeight * Math.sin(rads))); float rotatedHeight = (float) (Math.abs(textWidth * Math.sin(rads)) + Math.abs(textHeight * Math.cos(rads))); // 计算行列数(确保覆盖边界) int cols = (int) Math.ceil((pageWidth + rotatedWidth) / rotatedWidth); int rows = (int) Math.ceil((pageHeight + rotatedHeight) / rotatedHeight); // 添加偏移量覆盖边缘区域(关键优化点) float offsetX = -rotatedWidth / 2; float offsetY = -rotatedHeight / 2; // 平铺水印(全覆盖算法) for (int row = 0; row <= rows; row++) { float y = offsetY + row * rotatedHeight; // 交错布局(奇数行偏移) float rowOffset = (row % 2 == 0) ? 0 : rotatedWidth / 2; for (int col = 0; col <= cols; col++) { float x = offsetX + col * rotatedWidth + rowOffset; drawWatermark(stream, WATERMARK_TEXT, font, x + rotatedWidth/2, y + rotatedHeight/2); } } } catch (Exception e) { System.err.println("水印添加失败: " + e.getMessage()); } } private static void drawWatermark(PDPageContentStream stream, String text, PDType0Font font, float centerX, float centerY) throws IOException { stream.saveGraphicsState(); stream.beginText(); // 设置旋转中心(优化定位) stream.transform(Matrix.getRotateInstance( Math.toRadians(ROTATION_ANGLE), centerX, centerY)); // 计算文本偏移量(居中显示) float textOffsetX = -font.getStringWidth(text) * FONT_SIZE / 1000; float textOffsetY = -font.getFontDescriptor().getFontBoundingBox().getHeight() * FONT_SIZE / 1000; stream.newLineAtOffset(centerX + textOffsetX, centerY + textOffsetY); stream.showText(text); stream.endText(); stream.restoreGraphicsState(); }
09-02
=== 最优测线优化 === Traceback (most recent call last): File "c:\Users\Yeah\Desktop\数模\第七题\B题\33333.py", line 240, in <module> survey_lines, optimal_solution = design_optimal_survey_lines(beta=90) ~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^ File "c:\Users\Yeah\Desktop\数模\第七题\B题\33333.py", line 220, in design_optimal_survey_lines elif i <= len(overlaps) and not math.isnan(overlaps[i-1]): ~~~~~~~~~~^^^^^^^^^^^^^^^ TypeError: must be real number, not str import math import numpy as np # 参数设置 theta = 120 # 仪器开角 alpha = 1.5 # 入射角 D_center = 110 # 中心点水深 length_n_mile = 2 # 测线南北长度(海里) width_n_mile = 4 # 测线东西宽度(海里) overlap_min = 0.1 # 最小重叠率 overlap_max = 0.2 # 最大重叠率 # 单位转换 theta_rad = math.radians(theta) alpha_rad = math.radians(alpha) length_m = length_n_mile * 1852 # 南北长(米) width_m = width_n_mile * 1852 # 东西宽(米) def get_mu(beta): """计算μ角""" beta = beta % 360 if beta == 0 or beta == 180: return 0 elif beta == 90 or beta == 270: return 90 elif 0 < beta < 90: return 90 - beta elif 90 < beta < 180: return beta - 90 elif 180 < beta < 270: return 270 - beta else: return beta - 270 def get_lambda(alpha_rad, beta): """计算λ角""" if beta in [0, 180]: return alpha_rad elif beta in [90, 270]: return 0.0 else: mu_rad = math.radians(get_mu(beta)) return math.atan(math.tan(alpha_rad) * math.cos(mu_rad)) def get_angles(theta_rad, lambda_rad): """计算∠1与∠2""" angle1 = (math.pi - theta_rad) / 2 - lambda_rad angle2 = (math.pi - theta_rad) / 2 + lambda_rad return angle1, angle2 def get_depth(x, beta): """计算给定位置x的水深""" mu = get_mu(beta) mu_rad = math.radians(mu) lambda_rad = get_lambda(alpha_rad, beta) return D_center - (x - width_m / 2) * math.sin(alpha_rad) * math.sin(mu_rad) def coverage_width(x, beta): """计算给定位置x的覆盖宽度""" depth = get_depth(x, beta) lambda_rad = get_lambda(alpha_rad, beta) angle1, angle2 = get_angles(theta_rad, lambda_rad) sin_half_theta = math.sin(theta_rad / 2) W_1 = depth * sin_half_theta / math.sin(angle1) W_2 = depth * sin_half_theta / math.sin(angle2) return W_1 + W_2 def calculate_overlap_rate(prev_W_2, curr_W_1, d, alpha_rad, curr_W_1_plus_W_2): """计算重叠率""" if curr_W_1_plus_W_2 <= 0: return float('nan') overlap_width = prev_W_2 + curr_W_1 - d / math.cos(alpha_rad) return (overlap_width / curr_W_1_plus_W_2) * 100 def optimize_survey_lines(beta=90, min_overlap=0.1, max_overlap=0.2, precision=0.1): """优化测线方案""" # 计算中心点的覆盖宽度 center_coverage = coverage_width(length_m / 2, beta) # 有效测线间距范围 min_d = center_coverage * (1 - max_overlap) max_d = center_coverage * (1 - min_overlap) valid_solutions = [] best_solution = None # 遍历可能的测线间距 for d in np.arange(min_d, max_d, precision): num_lines = math.ceil(width_m / d) actual_d = width_m / num_lines # 验证所有测线的重叠率 valid = True overlaps = [] for i in range(1, num_lines): prev_x = (i-1) * actual_d curr_x = i * actual_d prev_depth = get_depth(prev_x, beta) prev_W_1 = prev_depth * math.sin(theta_rad/2) / math.sin( get_angles(theta_rad, get_lambda(alpha_rad, beta))[0]) prev_W_2 = prev_depth * math.sin(theta_rad/2) / math.sin( get_angles(theta_rad, get_lambda(alpha_rad, beta))[1]) curr_depth = get_depth(curr_x, beta) curr_W_1 = curr_depth * math.sin(theta_rad/2) / math.sin( get_angles(theta_rad, get_lambda(alpha_rad, beta))[0]) curr_W_2 = curr_depth * math.sin(theta_rad/2) / math.sin( get_angles(theta_rad, get_lambda(alpha_rad, beta))[1]) overlap_percent = calculate_overlap_rate( prev_W_2, curr_W_1, curr_x - prev_x, alpha_rad, curr_W_1 + curr_W_2) # 检查重叠率是否在要求范围内 if overlap_percent < min_overlap*100 or overlap_percent > max_overlap*100: valid = False break overlaps.append(overlap_percent) if valid: avg_overlap_deviation = sum(abs((overlap/100 - 0.15)/0.05) for overlap in overlaps) / len(overlaps) solution = { "测线间距": actual_d, "所需测线数量": num_lines, "总测线长度": num_lines * length_m / 1852, "平均重叠率偏离度": avg_overlap_deviation, "所有重叠率": overlaps.copy() } valid_solutions.append(solution) # 如果是当前最佳方案或首次找到有效解 if best_solution is None or (solution["总测线长度"] < best_solution["总测线长度"]): best_solution = solution # 如果没有找到有效解,返回最接近的候选解 if best_solution is None: candidate_solutions = [] for d in np.arange(min_d * 0.8, max_d * 1.2, precision * 5): # 扩大搜索范围 num_lines = math.ceil(width_m / d) actual_d = width_m / num_lines overlaps = [] valid = True for i in range(1, num_lines): prev_x = (i-1) * actual_d curr_x = i * actual_d prev_W_2 = get_depth(prev_x, beta) * math.sin(theta_rad/2) / math.sin( get_angles(theta_rad, get_lambda(alpha_rad, beta))[1]) curr_W_1 = get_depth(curr_x, beta) * math.sin(theta_rad/2) / math.sin( get_angles(theta_rad, get_lambda(alpha_rad, beta))[0]) curr_W_1_plus_W_2 = get_depth(curr_x, beta) * math.sin(theta_rad/2) / math.sin( get_angles(theta_rad, get_lambda(alpha_rad, beta))[0]) + \ get_depth(curr_x, beta) * math.sin(theta_rad/2) / math.sin( get_angles(theta_rad, get_lambda(alpha_rad, beta))[1]) overlap_percent = calculate_overlap_rate( prev_W_2, curr_W_1, curr_x - prev_x, alpha_rad, curr_W_1_plus_W_2) # 记录所有重叠率 overlaps.append(overlap_percent) # 检查重叠率是否接近要求范围 if overlap_percent < min_overlap*100 - 5 or overlap_percent > max_overlap*100 + 5: # 放宽条件 valid = False break if not valid: continue if overlaps: avg_overlap_deviation = sum(abs((overlap/100 - 0.15)/0.05) for overlap in overlaps if not math.isnan(overlap)) / len(overlaps) candidate_solutions.append({ "测线间距": actual_d, "所需测线数量": num_lines, "总测线长度": num_lines * length_m / 1852, "平均重叠率偏离度": avg_overlap_deviation if not math.isnan(avg_overlap_deviation) else float('inf'), "所有重叠率": overlaps.copy() }) # 按偏离度排序候选解 candidate_solutions.sort(key=lambda x: (x["平均重叠率偏离度"], x["总测线长度"])) if candidate_solutions: best_solution = candidate_solutions[0] else: # 如果所有方案都失败,返回默认方案 best_solution = { "测线间距": max_d / 1.5, # 选择中间值 "所需测线数量": math.ceil(width_m / (max_d / 1.5)), "总测线长度": math.ceil(width_m / (max_d / 1.5)) * length_m / 1852, "平均重叠率偏离度": float('inf'), "所有重叠率": ["无有效解"] } return best_solution def design_optimal_survey_lines(beta=90, min_overlap=0.1, max_overlap=0.2): """设计最优测线方案""" optimal_solution = optimize_survey_lines(beta, min_overlap, max_overlap) spacing = optimal_solution["测线间距"] num_lines = optimal_solution["所需测线数量"] overlaps = optimal_solution.get("所有重叠率", []) survey_lines = [] for i in range(num_lines): x = i * spacing depth = get_depth(x, beta) coverage = coverage_width(x, beta) # 处理重叠率信息 if i == 0: overlap_info = "首条测线,无重叠" elif i <= len(overlaps) and not math.isnan(overlaps[i-1]): overlap_info = f"{overlaps[i-1]:.2f}%" else: overlap_info = "计算异常" survey_lines.append({ "序号": i+1, "x坐标": x, "相对位置(海里)": x / 1852, "水深": depth, "覆盖宽度": coverage, "相邻重叠率(%)": overlap_info }) return survey_lines, optimal_solution if __name__ == "__main__": print("=== 最优测线优化 ===") # 获取最优测线方案 survey_lines, optimal_solution = design_optimal_survey_lines(beta=90) # 打印测线方案 print(f"\n最优测线方案 (β={90}°):") print(f"共需布设 {len(survey_lines)} 条测线") print(f"平均测线间距: {optimal_solution['测线间距']/1852:.2f} 海里") print(f"总测线长度: {optimal_solution['总测线长度']:.2f} 海里") print(f"平均重叠率偏离度: {optimal_solution['平均重叠率偏离度']:.2f}") print("\n详细测线信息:") for line in survey_lines: print(f"测线 {line['序号']}: " f"x坐标 = {line['x坐标']:.2f} 米, " f"相对位置 = {line['相对位置(海里)']:.2f} 海里, " f"水深 = {line['水深']:.2f} 米, " f"覆盖宽度 = {line['覆盖宽度']:.2f} 米, " f"相邻重叠率 = {line['相邻重叠率(%)']}") 、
08-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值