show_cos.c

  name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-5572165936844014&dt=1194442938015&lmt=1194190197&format=336x280_as&output=html&correlator=1194442937843&url=file%3A%2F%2F%2FC%3A%2FDocuments%2520and%2520Settings%2Flhh1%2F%E6%A1%8C%E9%9D%A2%2FCLanguage.htm&color_bg=FFFFFF&color_text=000000&color_link=000000&color_url=FFFFFF&color_border=FFFFFF&ad_type=text&ga_vid=583001034.1194442938&ga_sid=1194442938&ga_hid=1942779085&flash=9&u_h=768&u_w=1024&u_ah=740&u_aw=1024&u_cd=32&u_tz=480&u_java=true" frameborder="0" width="336" scrolling="no" height="280" allowtransparency="allowtransparency"> #include <stdio.h>
#include <math.h>

void main(void)
 {
   printf("cosine of pi/2 is %6.4f/n", cos(3.14159/2.0));
   printf("cosine of pi is %6.4f/n", cos(3.14159));
 }

[num, ~, ~] = xlsread('C:\Users\f\Desktop\数学建模\final\B题\附件\滤波后反射率数据.xlsx'); bo_shu= num(2:end, 1); fan_she_lv_smooth =num(2:end, 3); sita_i=10; function R=ideal_R_model(params,bo_shu,sita_i) d=params(1); A=params(2); B=params(3); C=params(4); D=params(5); E=params(6); F=params(7); G=params(8); H=params(9); sita_i=deg2rad(10); % fprintf('弧度:%.6f\n',sita_i); n1=A+B*bo_shu+C*bo_shu.^2; k1=D+E*bo_shu+F*bo_shu.^2; n2=G+H*bo_shu; n1_fu=n1+1i*k1; n2_fu=n2; sita_r=asin(sin(sita_i)./n1_fu); sita_c=asin(sin(sita_i)./n2_fu); r1_s=(cos(sita_i)-n1_fu.*cos(sita_r))./(cos(sita_i)+n1_fu.*cos(sita_r)); r2_s=(n1_fu.*cos(sita_r)-n2_fu.*cos(sita_c))./(n1_fu.*cos(sita_r)+n2_fu.*cos(sita_c)); r1_p = (n1_fu .* cos(sita_i) - cos(sita_r)) ./ (n1_fu .* cos(sita_i) + cos(sita_r)); r2_p = (n2_fu .* cos(sita_r) - n1_fu .* cos(sita_c)) ./ (n2_fu .* cos(sita_r) + n1_fu .* cos(sita_c)); beta=2*pi*bo_shu.*n1_fu*d.*cos(sita_r); r_s = (r1_s + r2_s .* exp(-2i * beta)) ./ (1 + r1_s .* r2_s .* exp(-2i * beta)); r_p = (r1_p + r2_p .* exp(-2i * beta)) ./ (1 + r1_p .* r2_p .* exp(-2i * beta)); R=(abs(r_s).^2+abs(r_p).^2)/2; end function residuals = residual_function(params, bo_shu, fan_she_lv_smooth, sita_i) R_theoretical = ideal_R_model(params, bo_shu, sita_i); residuals = fan_she_lv_smooth - R_theoretical; end options = optimoptions('lsqnonlin','Display', 'iter', 'MaxIterations', 1000,'FunctionTolerance', 1e-8,'StepTolerance', 1e-10,'OptimalityTolerance', 1e-6, ... 'Algorithm', 'trust-region-reflective','FiniteDifferenceType', 'central', 'MaxFunctionEvaluations', 10000); % initial_params = [2e-3,1e-6,-8.476389e-03,1.456919e+01,0,0,0,2.55,0]; % % lb = [1e-4; 1e-7; -1e-4; 0; 0; -1e-6; -1e-10; 2.5; -1e-5]; % ub = [1e-3; 1e-5; 1e-4; 2e+8; 0.1; 1e-6; 1e-10; 3.0; 1e-5]; sita_i = deg2rad(10); residual_func = @(params) residual_function(params, bo_shu, fan_she_lv_smooth, sita_i); [optimal_params, resnorm, residual, exitflag, output] = lsqnonlin(residual_func, initial_params, lb, ub, options); fprintf('优化完成!\n'); fprintf('\n最优参数:\n'); fprintf('d = %.6f μm\n', optimal_params(1) * 1e4); fprintf('A = %.6f\n', optimal_params(2)); fprintf('B = %.6e\n', optimal_params(3)); fprintf('C = %.6e\n', optimal_params(4)); fprintf('D = %.6f\n', optimal_params(5)); fprintf('E = %.6e\n', optimal_params(6)); fprintf('F = %.6e\n', optimal_params(7)); fprintf('G = %.6f\n', optimal_params(8)); fprintf('H = %.6e\n', optimal_params(9)); figure('Position', [100, 100, 800, 600]); plot(bo_shu, fan_she_lv_smooth, 'b-'); hold on; plot(bo_shu, R_theoretical, 'r--' ); xlabel('波数 '); ylabel('反射率'); legend('show', 'Location', 'best'); title('反射率光谱拟合结果'); grid on;
09-07
import matplotlib.pyplot as plt def plot_client_pos_sim(clients, pos_sim_list): fig, ax = plt.subplots(figsize=(10, 6)) x = np.arange(len(clients)) # the label locations plt.plot(x, pos_sim_list, linestyle='-', color='blue') interval = 5 ax.set_xticks(x[::interval]) ax.set_xticklabels([clients[i] for i in range(0, len(clients), interval)], rotation=45) plt.title("Position Similarity Over Clients") plt.xlabel("Clients") plt.ylabel("Position Similarity") plt.grid(True) plt.xticks(rotation=45) plt.tight_layout() plt.show() daily_positions_cos.sort_values(by=["pos_sim"], inplace=True) plot_client_pos_sim(daily_positions_cos["client_id"], daily_positions_cos["pos_sim"]) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) File c:\Users\matianht\.conda\envs\nomura\lib\site-packages\pandas\core\indexes\base.py:3805, in Index.get_loc(self, key) 3804 try: -> 3805 return self._engine.get_loc(casted_key) 3806 except KeyError as err: File index.pyx:167, in pandas._libs.index.IndexEngine.get_loc() File index.pyx:191, in pandas._libs.index.IndexEngine.get_loc() File index.pyx:228, in pandas._libs.index.IndexEngine._get_loc_duplicates() KeyError: 5 The above exception was the direct cause of the following exception: KeyError Traceback (most recent call last) Cell In[162], line 25 21 plt.show() 23 daily_positions_cos.sort_values(by=["pos_sim"], inplace=True) ---> 25 plot_client_pos_sim(daily_positions_cos["client_id"], daily_positions_cos["pos_sim"]) Cell In[162], line 11, in plot_client_pos_sim(clients, pos_sim_list) 9 interval = 5 10 ax.set_xticks(x[::interval]) ---> 11 ax.set_xticklabels([clients[i] for i in range(0, len(clients), interval)], rotation=45) 13 plt.title("Position Similarity Over Clients") 14 plt.xlabel("Clients") Cell In[162], line 11, in <listcomp>(.0) 9 interval = 5 10 ax.set_xticks(x[::interval]) ---> 11 ax.set_xticklabels([clients[i] for i in range(0, len(clients), interval)], rotation=45) 13 plt.title("Position Similarity Over Clients") 14 plt.xlabel("Clients") File c:\Users\matianht\.conda\envs\nomura\lib\site-packages\pandas\core\series.py:1121, in Series.__getitem__(self, key) 1118 return self._values[key] 1120 elif key_is_scalar: -> 1121 return self._get_value(key) 1123 # Convert generator to list before going through hashable part 1124 # (We will iterate through the generator there to check for slices) 1125 if is_iterator(key): File c:\Users\matianht\.conda\envs\nomura\lib\site-packages\pandas\core\series.py:1237, in Series._get_value(self, label, takeable) 1234 return self._values[label] 1236 # Similar to Index.get_value, but we do not fall back to positional -> 1237 loc = self.index.get_loc(label) 1239 if is_integer(loc): 1240 return self._values[loc] File c:\Users\matianht\.conda\envs\nomura\lib\site-packages\pandas\core\indexes\base.py:3812, in Index.get_loc(self, key) 3807 if isinstance(casted_key, slice) or ( 3808 isinstance(casted_key, abc.Iterable) 3809 and any(isinstance(x, slice) for x in casted_key) 3810 ): 3811 raise InvalidIndexError(key) -> 3812 raise KeyError(key) from err 3813 except TypeError: 3814 # If we have a listlike key, _check_indexing_error will raise 3815 # InvalidIndexError. Otherwise we fall through and re-raise 3816 # the TypeError. 3817 self._check_indexing_error(key) KeyError: 5 检查一下错误
07-30
# FOC voltage space vector animation (SVPWM-style) # Save as e.g. foc_space_vector.py and run: python foc_space_vector.py # Requirements: numpy, matplotlib import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Parameters V_mag = 1.0 # reference vector magnitude f = 1.0 # electrical frequency (Hz) omega = 2 * np.pi * f fs = 60 # animation frames per second duration = 6 # seconds frames = int(duration * fs) t_vals = np.linspace(0, duration, frames) # Clarke inverse (alpha-beta -> a,b,c) def alpha_beta_to_abc(alpha, beta): va = alpha vb = -0.5 * alpha + np.sqrt(3)/2 * beta vc = -0.5 * alpha - np.sqrt(3)/2 * beta return va, vb, vc # phase axis unit vectors in alpha-beta plane u_a = np.array([1.0, 0.0]) u_b = np.array([np.cos(-2*np.pi/3), np.sin(-2*np.pi/3)]) u_c = np.array([np.cos(2*np.pi/3), np.sin(2*np.pi/3)]) # Set up figure fig = plt.figure(figsize=(8, 6)) ax_ab = fig.add_subplot(2, 1, 1) ax_traces = fig.add_subplot(2, 1, 2) # Alpha-beta plane limits R = 1.2 * V_mag ax_ab.set_xlim(-R, R) ax_ab.set_ylim(-R, R) ax_ab.set_aspect('equal', 'box') ax_ab.set_title('Voltage Space Vector (α-β plane)') ax_ab.set_xlabel('α') ax_ab.set_ylabel('β') ax_ab.grid(True) # Draw hexagon (SVPWM switching states approximate) angles = np.linspace(np.pi/6, np.pi/6 + 2*np.pi, 7) hex_x = V_mag * np.cos(angles) hex_y = V_mag * np.sin(angles) ax_ab.plot(hex_x, hex_y, 'k--', alpha=0.6) # draw phase axes for u, label in zip((u_a, u_b, u_c), ('A', 'B', 'C')): ax_ab.arrow(0, 0, 0.9*R*u[0], 0.9*R*u[1], head_width=0.04*R, head_length=0.06*R, fc='gray', ec='gray', linestyle=':') ax_ab.text(1.02*R*u[0], 1.02*R*u[1], label, color='gray', fontsize=10, ha='center', va='center') # reference vector arrow ref_arrow = ax_ab.arrow(0, 0, 0, 0, head_width=0.04*R, head_length=0.06*R, color='r') # projections to phase axes (lines) proj_lines = [ ax_ab.plot([0, 0], [0, 0], 'r--', linewidth=1)[0], ax_ab.plot([0, 0], [0, 0], 'g--', linewidth=1)[0], ax_ab.plot([0, 0], [0, 0], 'b--', linewidth=1)[0], ] # moving dots on hexagon/circle dot_ref, = ax_ab.plot([0], [0], 'ro') # Time traces for phase voltages ax_traces.set_title('Phase voltages (a,b,c)') ax_traces.set_xlabel('Time (s)') ax_traces.set_ylabel('Voltage (pu)') ax_traces.set_xlim(0, duration) ax_traces.set_ylim(-1.2*V_mag, 1.2*V_mag) ax_traces.grid(True) line_va, = ax_traces.plot([], [], 'r-', label='va') line_vb, = ax_traces.plot([], [], 'g-', label='vb') line_vc, = ax_traces.plot([], [], 'b-', label='vc') ax_traces.legend(loc='upper right') # storage for traces t_history = [] va_history = [] vb_history = [] vc_history = [] def init(): global ref_arrow ref_arrow.remove() ref_arrow = ax_ab.arrow(0, 0, 0, 0, head_width=0.04*R, head_length=0.06*R, color='r') dot_ref.set_data([], []) for l in proj_lines: l.set_data([], []) line_va.set_data([], []) line_vb.set_data([], []) line_vc.set_data([], []) t_history.clear() va_history.clear() vb_history.clear() vc_history.clear() return [ref_arrow, dot_ref, *proj_lines, line_va, line_vb, line_vc] def update(frame): t = t_vals[frame] theta = omega * t # reference vector in alpha-beta alpha = V_mag * np.cos(theta) beta = V_mag * np.sin(theta) # phase voltages from Clarke inverse va, vb, vc = alpha_beta_to_abc(alpha, beta) # update ref arrow (remove and redraw because matplotlib arrow isn't easily updated) global ref_arrow try: ref_arrow.remove() except Exception: pass ref_arrow = ax_ab.arrow(0, 0, alpha, beta, head_width=0.04*R, head_length=0.06*R, color='r') dot_ref.set_data(alpha, beta) # projection lines onto phase axes (from origin to projection point) for u, line, color, vall in zip((u_a, u_b, u_c), proj_lines, ('r', 'g', 'b'), (va, vb, vc)): proj_point = vall * u # projection magnitude times unit axis line.set_data([0, proj_point[0]], [0, proj_point[1]]) line.set_color(color) # update traces t_history.append(t) va_history.append(va) vb_history.append(vb) vc_history.append(vc) # keep only recent window to match xlim line_va.set_data(t_history, va_history) line_vb.set_data(t_history, vb_history) line_vc.set_data(t_history, vc_history) return [ref_arrow, dot_ref, *proj_lines, line_va, line_vb, line_vc] ani = animation.FuncAnimation(fig, update, frames=frames, init_func=init, blit=False, interval=1000/fs, repeat=True) plt.tight_layout() plt.show() 将上面代码完善
11-18
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值