-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1685 lines (1457 loc) · 65.7 KB
/
script.js
File metadata and controls
1685 lines (1457 loc) · 65.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 基本功能函数
function toggleGuide() {
const guideContent = document.querySelector('.guide-content');
if (guideContent) {
guideContent.style.display = guideContent.style.display === 'none' ? 'block' : 'none';
}
}
// 添加变量
function addVariable() {
const container = document.getElementById('variables-container');
const varDiv = document.createElement('div');
varDiv.className = 'variable-row';
varDiv.innerHTML = `
<input type="text" placeholder="变量名" class="var-name">
<textarea class="var-data" placeholder="输入多组数据,用逗号或空格分隔"></textarea>
<input type="number" placeholder="仪器精度" class="var-precision" step="any">
<input type="text" placeholder="单位" class="var-unit">
<div class="uncertainty-controls">
<select class="uncertainty-type">
<option value="a">A类</option>
<option value="b">B类</option>
</select>
</div>
<div class="variable-actions">
<button onclick="removeVariable(this)">删除</button>
<button onclick="calculateVariableStats(this)">计算统计量</button>
</div>
`;
container.appendChild(varDiv);
updateVariableSelects();
}
// 删除变量
function removeVariable(button) {
const row = button.closest('.variable-row');
if (row) {
row.remove();
updateVariableSelects();
}
}
// 更新变量选择下拉框
function updateVariableSelects() {
const variables = Array.from(document.getElementsByClassName('var-name'))
.map(input => input.value)
.filter(name => name);
document.querySelectorAll('.x-axis, .y-axis').forEach(select => {
const currentValue = select.value;
select.innerHTML = '';
variables.forEach(varName => {
const option = document.createElement('option');
option.value = varName;
option.textContent = varName;
select.appendChild(option);
});
if (variables.includes(currentValue)) {
select.value = currentValue;
}
});
}
// 计算变量统计量
function calculateVariableStats(button) {
const row = button.closest('.variable-row');
if (!row) return;
const name = row.querySelector('.var-name').value;
const dataText = row.querySelector('.var-data').value;
const precision = parseFloat(row.querySelector('.var-precision').value);
const uncertaintyType = row.querySelector('.uncertainty-type').value;
// 解析数据
const data = dataText.split(/[,\s]+/).map(Number).filter(x => !isNaN(x));
if (data.length < 1) {
alert('需要至少1个有效的数据点');
return;
}
// 计算统计量
const mean = data.reduce((a, b) => a + b) / data.length;
const variance = data.length > 1 ?
data.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / (data.length - 1) : 0;
const standardDeviation = Math.sqrt(variance);
// 计算不确定度
let uncertainty;
if (uncertaintyType === 'a' && data.length > 1) {
uncertainty = standardDeviation / Math.sqrt(data.length);
} else {
uncertainty = precision / Math.sqrt(3);
}
// 存储计算结果
row.dataset.stats = JSON.stringify({
name,
mean,
standardDeviation,
uncertainty,
unit: row.querySelector('.var-unit').value
});
// 显示统计结果
const statsDiv = row.querySelector('.variable-stats') || document.createElement('div');
statsDiv.className = 'variable-stats';
statsDiv.innerHTML = `
<div class="stats-section">
<h4>统计结果</h4>
<p>平均值:${mean.toFixed(6)}</p>
<p>标准差:${standardDeviation.toFixed(6)}</p>
<p>不确定度:${uncertainty.toFixed(6)}</p>
<p>数据点数:${data.length}</p>
</div>
`;
if (!row.querySelector('.variable-stats')) {
row.appendChild(statsDiv);
}
}
// 修约规则对象
const RoundingRules = {
// 获取有效数字的位数
getSignificantDigits(value, uncertainty) {
const scientificUncertainty = this.toScientific(uncertainty);
const firstSignificantDigit = Math.floor(Math.log10(scientificUncertainty.value));
const firstDigit = Math.floor(scientificUncertainty.value / Math.pow(10, firstSignificantDigit));
let decimalPlaces;
if (firstDigit <= 2) {
decimalPlaces = -firstSignificantDigit + 1;
} else {
decimalPlaces = -firstSignificantDigit;
}
return {
decimalPlaces,
scientificNotation: this.toScientific(value)
};
},
// 转换为科学记数法
toScientific(number) {
const exponent = Math.floor(Math.log10(Math.abs(number)));
const value = number / Math.pow(10, exponent);
return { value, exponent };
},
// 修约数值
roundValue(value, uncertainty) {
const { decimalPlaces } = this.getSignificantDigits(value, uncertainty);
return this.roundToDecimalPlaces(value, decimalPlaces);
},
// 修约不确定度
roundUncertainty(uncertainty) {
const scientific = this.toScientific(uncertainty);
const firstDigit = Math.floor(scientific.value);
const decimalPlaces = firstDigit <= 2 ? 1 : 0;
return this.roundToDecimalPlaces(uncertainty, -scientific.exponent + decimalPlaces);
},
// 按小数位数修约
roundToDecimalPlaces(number, places) {
const factor = Math.pow(10, places);
return Math.round(number * factor) / factor;
},
// 格式化最终结果
formatFinalResult(value, uncertainty, unit) {
const roundedValue = this.roundValue(value, uncertainty);
const roundedUncertainty = this.roundUncertainty(uncertainty);
const valueScientific = this.toScientific(roundedValue);
const uncertaintyScientific = this.toScientific(roundedUncertainty);
const useScientific = Math.abs(valueScientific.exponent) > 4;
if (useScientific) {
return {
formatted: `(${(valueScientific.value).toFixed(2)} ± ${(uncertaintyScientific.value).toFixed(2)}) × 10^${valueScientific.exponent} ${unit}`,
value: roundedValue,
uncertainty: roundedUncertainty
};
} else {
return {
formatted: `(${roundedValue} ± ${roundedUncertainty}) ${unit}`,
value: roundedValue,
uncertainty: roundedUncertainty
};
}
}
};
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
// 检查是否是首次访问
if (!localStorage.getItem('hasVisited')) {
document.querySelector('.guide-content').style.display = 'block';
localStorage.setItem('hasVisited', 'true');
}
addVariable();
});
// 修改计算结果函数以处理多表达式并增强错误处理
function calculateResult() {
const formula = document.getElementById('formula').value.trim(); // 添加trim()去除空白字符
const resultsContainer = document.getElementById('results-container');
if (!formula) {
resultsContainer.innerHTML = '<p class="error">请填写公式。</p>';
return;
}
try {
// 创建计算步骤容器
const calculationSteps = document.createElement('div');
calculationSteps.className = 'calculation-steps';
// 第1步:收集变量数据
const variableStep = document.createElement('div');
variableStep.className = 'step';
const scope = { pi: Math.PI, e: Math.E };
const uncertainties = {};
const variableData = {};
document.querySelectorAll('.variable-row').forEach(row => {
const name = row.querySelector('.var-name').value.trim();
if (!name) return;
try {
const stats = JSON.parse(row.dataset.stats || '{}');
if (stats.mean !== undefined) {
scope[name] = stats.mean;
uncertainties[name] = stats.uncertainty;
variableData[name] = {
mean: stats.mean,
uncertainty: stats.uncertainty,
unit: stats.unit
};
}
} catch (e) {
console.warn(`解析变量 ${name} 的统计数据时出错:`, e);
}
});
// 第2步:计算表达式
const expressions = formula.split(';').filter(expr => expr.trim());
let mainResult;
expressions.forEach((expr, index) => {
const result = math.evaluate(expr, scope);
const assignMatch = expr.match(/(\w+)\s*=\s*(.+)/);
if (assignMatch) {
const varName = assignMatch[1];
scope[varName] = result;
if (index === expressions.length - 1) {
mainResult = { name: varName, value: result };
}
}
});
// 第3步:计算不确定度传递
if (mainResult) {
const mainExpr = expressions[expressions.length - 1].split('=')[1].trim();
const parsedExpr = math.parse(mainExpr);
const variables = Object.keys(scope).filter(v => v !== 'pi' && v !== 'e');
let uncertaintySum = 0;
const uncertaintyTerms = [];
variables.forEach(variable => {
if (uncertainties[variable]) {
try {
const derivative = math.derivative(parsedExpr, variable);
const derivativeValue = derivative.evaluate(scope);
const contribution = Math.pow(derivativeValue * uncertainties[variable], 2);
uncertaintySum += contribution;
uncertaintyTerms.push({
variable,
derivative: derivative.toString(),
derivativeValue,
uncertainty: uncertainties[variable],
contribution: Math.sqrt(contribution)
});
} catch (e) {
console.warn(`计算变量 ${variable} 的不确定度贡献时出错:`, e);
}
}
});
const totalUncertainty = Math.sqrt(uncertaintySum);
const relativeUncertainty = (totalUncertainty / Math.abs(mainResult.value)) * 100;
// 显示计算结果
calculationSteps.innerHTML = `
<div class="step">
<h4>1. 变量及其不确定度</h4>
${Object.entries(variableData).map(([name, data]) =>
`<p>${name} = ${data.mean.toFixed(6)} ± ${data.uncertainty.toFixed(6)} ${data.unit}</p>`
).join('')}
</div>
<div class="step">
<h4>2. 不确定度传递计算</h4>
${uncertaintyTerms.map(term => `
<div class="uncertainty-term">
<p>∂(${mainResult.name})/∂${term.variable} = ${term.derivative}</p>
<p>值 = ${term.derivativeValue.toFixed(6)}</p>
<p>贡献 = ${term.contribution.toFixed(6)}</p>
</div>
`).join('')}
</div>
<div class="step">
<h4>3. 最终结果</h4>
<p>计算值:${mainResult.value.toFixed(6)}</p>
<p>合成标准不确定度:${totalUncertainty.toFixed(6)}</p>
<p>相对不确定度:${relativeUncertainty.toFixed(2)}%</p>
<p>扩展不确定度(k=2):${(2 * totalUncertainty).toFixed(6)}</p>
<p class="final-result">${mainResult.name} = (${mainResult.value.toFixed(6)} ± ${(2 * totalUncertainty).toFixed(6)})</p>
</div>
`;
resultsContainer.innerHTML = '';
resultsContainer.appendChild(calculationSteps);
}
} catch (error) {
resultsContainer.innerHTML = `
<p class="error">计算错误:${error.message}</p>
<p>请检查:</p>
<ul>
<li>所有变量是否已正确计算统计量</li>
<li>公式格式是否正确(每个表达式用分号分隔)</li>
<li>变量名是否与输入匹配</li>
<li>数学运算符是否使用正确</li>
</ul>
`;
}
}
// 获取变量单位
function getUnit(variableName) {
const variableRow = Array.from(document.getElementsByClassName('variable-row'))
.find(row => row.querySelector('.var-name').value === variableName);
return variableRow ? variableRow.querySelector('.var-unit').value : '';
}
// 添加示例数据加载函数
async function loadExample() {
try {
// 清除现有数据和结果
document.getElementById('variables-container').innerHTML = '';
document.getElementById('results-container').innerHTML = '';
const variables = [
{
name: 'm',
data: '0.050, 0.100, 0.150, 0.200, 0.250',
precision: '0.0001',
unit: 'kg',
type: 'b'
},
{
name: 'y',
data: '0.52, 1.05, 1.58, 2.10, 2.63',
precision: '0.01',
unit: 'mm',
type: 'b'
},
{
name: 'd',
data: '0.35',
precision: '0.01',
unit: 'mm',
type: 'b'
},
{
name: 'D',
data: '25.00',
precision: '0.02',
unit: 'mm',
type: 'b'
},
{
name: 'L',
data: '800',
precision: '1',
unit: 'mm',
type: 'b'
}
];
// 初始化变量
for (const v of variables) {
addVariable();
const rows = document.querySelectorAll('.variable-row');
const lastRow = rows[rows.length - 1];
lastRow.querySelector('.var-name').value = v.name;
lastRow.querySelector('.var-data').value = v.data;
lastRow.querySelector('.var-precision').value = v.precision;
lastRow.querySelector('.var-unit').value = v.unit;
lastRow.querySelector('.uncertainty-type').value = v.type;
// 计算并等待统计量计算完成
const calcButton = lastRow.querySelector('button[onclick="calculateVariableStats(this)"]');
calculateVariableStats(calcButton);
await new Promise(resolve => setTimeout(resolve, 100));
}
// 设置计算公式
const formulaInput = document.getElementById('formula');
formulaInput.value = `L_m = L/1000;
d_m = d/1000;
D_m = D/1000;
E = (4 * m * 9.794 * (L_m^3))/(pi * (d_m^2) * (D_m^2))`;
// 等待一会儿确保所有变量都已准备好
await new Promise(resolve => setTimeout(resolve, 500));
// 执行计算
calculateResult();
// 更新图表
updatePlot();
} catch (error) {
console.error('加载示例数据时出错:', error);
document.getElementById('results-container').innerHTML = `
<p class="error">加载示例数据时出错: ${error.message}</p>
`;
}
}
// 更新图表函数
function updatePlot() {
const showErrorBars = document.getElementById('show-error-bars').checked;
const autoRange = document.getElementById('auto-range').checked;
const traces = [];
document.querySelectorAll('.curve-row').forEach(row => {
const xVar = row.querySelector('.x-axis').value;
const yVar = row.querySelector('.y-axis').value;
const showFit = row.querySelector('.show-fit').checked;
const fitType = row.querySelector('.fit-type').value;
// 获取数据
const xRow = Array.from(document.querySelectorAll('.variable-row'))
.find(r => r.querySelector('.var-name').value === xVar);
const yRow = Array.from(document.querySelectorAll('.variable-row'))
.find(r => r.querySelector('.var-name').value === yVar);
if (xRow && yRow) {
const xData = xRow.querySelector('.var-data').value.split(/[,\s]+/).map(Number);
const yData = yRow.querySelector('.var-data').value.split(/[,\s]+/).map(Number);
const xStats = JSON.parse(xRow.dataset.stats || '{}');
const yStats = JSON.parse(yRow.dataset.stats || '{}');
// 创建数据点轨迹
const dataTrace = {
x: xData,
y: yData,
error_x: {
type: 'data',
array: Array(xData.length).fill(xStats.uncertainty || 0),
visible: showErrorBars
},
error_y: {
type: 'data',
array: Array(yData.length).fill(yStats.uncertainty || 0),
visible: showErrorBars
},
mode: 'markers',
type: 'scatter',
name: `${yVar} vs ${xVar} (数据点)`
};
traces.push(dataTrace);
// 如果需要显示拟合线
if (showFit && xData.length > 1) {
const fitResult = applyFit(xData, yData, fitType);
// 生成拟合线
let fitTrace;
if (fitType === 'polynomial') {
const xFit = [];
const yFit = [];
const step = (Math.max(...xData) - Math.min(...xData)) / 100;
for (let x = Math.min(...xData); x <= Math.max(...xData); x += step) {
xFit.push(x);
yFit.push(fitResult.coefficients.reduce((sum, coef, i) =>
sum + coef * Math.pow(x, i), 0));
}
fitTrace = {
x: xFit,
y: yFit,
mode: 'lines',
type: 'scatter',
name: `多项式拟合`,
line: { color: 'red' }
};
} else {
// 现有的拟合线代码
varDiv.className = 'variable-row';
varDiv.innerHTML = `
<input type="text" placeholder="变量名" class="var-name" value="${v.name}">
<textarea class="var-data" placeholder="输入多组数据,用逗号或空格分隔">${v.data}</textarea>
<input type="number" placeholder="仪器精度" class="var-precision" step="any" value="${v.precision}">
<input type="text" placeholder="单位" class="var-unit" value="${v.unit}">
<div class="uncertainty-controls">
<select class="uncertainty-type">
<option value="a" ${v.type === 'a' ? 'selected' : ''}>A类</option>
<option value="b" ${v.type === 'b' ? 'selected' : ''}>B类</option>
</select>
</div>
<div class="variable-actions">
<button onclick="removeVariable(this)">删除</button>
<button onclick="calculateVariableStats(this)">计算统计量</button>
</div>
`;
document.getElementById('variables-container').appendChild(varDiv);
// 计算统计量并等待完成
await new Promise(resolve => {
const calcButton = varDiv.querySelector('.variable-actions button:last-child');
calcButton.click();
setTimeout(resolve, 100);
});
}
// 更新变量选择
updateVariableSelects();
// 设置计算公式
const formulaInput = document.getElementById('formula');
formulaInput.value = `L_m = L/1000;
d_m = d/1000;
D_m = D/1000;
E = (4 * m * 9.794 * (L_m^3))/(pi * (d_m^2) * (D_m^2))`;
// 等待所有数据准备完成后计算结果
setTimeout(calculateResult, 500);
};
// 执行初始化
initializeVariables().catch(error => {
console.error('初始化变量时出错:', error);
});
}
// 更新图表函数
function updatePlot() {
const showErrorBars = document.getElementById('show-error-bars').checked;
const autoRange = document.getElementById('auto-range').checked;
const traces = [];
document.querySelectorAll('.curve-row').forEach(row => {
const xVar = row.querySelector('.x-axis').value;
const yVar = row.querySelector('.y-axis').value;
const showFit = row.querySelector('.show-fit').checked;
const fitType = row.querySelector('.fit-type').value;
// 获取数据
const xRow = Array.from(document.querySelectorAll('.variable-row'))
.find(r => r.querySelector('.var-name').value === xVar);
const yRow = Array.from(document.querySelectorAll('.variable-row'))
.find(r => r.querySelector('.var-name').value === yVar);
if (xRow && yRow) {
const xData = xRow.querySelector('.var-data').value.split(/[,\s]+/).map(Number);
const yData = yRow.querySelector('.var-data').value.split(/[,\s]+/).map(Number);
const xStats = JSON.parse(xRow.dataset.stats || '{}');
const yStats = JSON.parse(yRow.dataset.stats || '{}');
// 创建数据点轨迹
const dataTrace = {
x: xData,
y: yData,
error_x: {
type: 'data',
array: Array(xData.length).fill(xStats.uncertainty || 0),
visible: showErrorBars
},
error_y: {
type: 'data',
array: Array(yData.length).fill(yStats.uncertainty || 0),
visible: showErrorBars
},
mode: 'markers',
type: 'scatter',
name: `${yVar} vs ${xVar} (数据点)`
};
traces.push(dataTrace);
// 如果需要显示拟合线
if (showFit && xData.length > 1) {
const fitResult = applyFit(xData, yData, fitType);
// 生成拟合线
let fitTrace;
if (fitType === 'polynomial') {
const xFit = [];
const yFit = [];
const step = (Math.max(...xData) - Math.min(...xData)) / 100;
for (let x = Math.min(...xData); x <= Math.max(...xData); x += step) {
xFit.push(x);
yFit.push(fitResult.coefficients.reduce((sum, coef, i) =>
sum + coef * Math.pow(x, i), 0));
}
fitTrace = {
x: xFit,
y: yFit,
mode: 'lines',
type: 'scatter',
name: `多项式拟合`,
line: { color: 'red' }
};
} else {
// 现有的拟合线代码
const { slope, intercept, correlation } = linearFit(xData, yData);
// 生成拟合线数据点
const xFit = [Math.min(...xData), Math.max(...xData)];
const yFit = xFit.map(x => slope * x + intercept);
fitTrace = {
x: xFit,
y: yFit,
mode: 'lines',
type: 'scatter',
name: `拟合线: ${yVar} = (${slope.toFixed(4)})${xVar} + (${intercept.toFixed(4)})`,
line: { color: 'red' }
};
}
traces.push(fitTrace);
// ���储拟合参数供后续使用
window.fitParameters = {
slope,
intercept,
correlation,
xVar,
yVar
};
}
}
});
// 设置布局
const layout = {
title: '数据拟合图',
showlegend: true,
legend: {
x: 1,
xanchor: 'right',
y: 1
},
xaxis: { title: '自变量' },
yaxis: { title: '因变量' }
};
if (!autoRange) {
layout.xaxis.range = [
parseFloat(document.getElementById('x-min').value),
parseFloat(document.getElementById('x-max').value)
];
layout.yaxis.range = [
parseFloat(document.getElementById('y-min').value),
parseFloat(document.getElementById('y-max').value)
];
}
// 绘制图表
Plotly.newPlot('plot-canvas', traces, layout, {
responsive: true,
scrollZoom: true,
displayModeBar: true,
modeBarButtonsToAdd: ['drawopenpath', 'eraseshape']
});
}
// 线性拟合函数
function linearFit(xData, yData) {
const n = xData.length;
let sumX = 0, sumY = 0, sumXY = 0, sumXX = 0, sumYY = 0;
for (let i = 0; i < n; i++) {
sumX += xData[i];
sumY += yData[i];
sumXY += xData[i] * yData[i];
sumXX += xData[i] * xData[i];
sumYY += yData[i] * yData[i];
}
const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
const intercept = (sumY - slope * sumX) / n;
// 计算相关系数
const correlation = (n * sumXY - sumX * sumY) /
Math.sqrt((n * sumXX - sumX * sumX) * (n * sumYY - sumY * sumY));
return { slope, intercept, correlation };
}
// 添加提取变量函数
function extractVariables(formula) {
// 移除所有空格和注释
const cleanFormula = formula.replace(/\/\/.*$/gm, '') // 移除单行注释
.replace(/\/\*[\s\S]*?\*\//g, '') // 移除多行注释
.replace(/\s+/g, ''); // 移除空格
// 替换 'π' 为 'pi'
const normalizedFormula = cleanFormula.replace(/π/g, 'pi');
// 移除数字(包括科学记数法)
const noNumbers = noFunctions.replace(/[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?/g, '');
// 移除数学运算符和括号
const noOperators = noNumbers.replace(/[+\-*/^()=,]/g, ' ');
// 匹配所有合法的变量名(字母开头,可包含字母、数字和下划线)
const matches = noOperators.match(/[a-zA-Z][a-zA-Z0-9_]*/g) || [];
// 过滤掉数学常量和重复项
const constants = ['pi', 'e', 'i'];
const variables = [...new Set(matches)].filter(v => !constants.includes(v));
return variables;
}
// 修改生成不确定度公式函数
function generateUncertaintyFormula() {
const formula = document.getElementById('formula').value;
const uncertaintyFormulaField = document.getElementById('uncertainty-formula');
try {
// 分割多个表达式
const expressions = formula.split(';').map(expr => expr.trim());
// 获取最后一个表达式(主要计算公式)
const mainExpr = expressions[expressions.length - 1];
// 检查是否是赋值表达式
const assignmentMatch = mainExpr.match(/(\w+)\s*=\s*(.+)/);
if (!assignmentMatch) {
throw new Error('最后一个表达式必���是赋值形式(例如:E = ...)');
}
const resultVariable = assignmentMatch[1];
const expression = assignmentMatch[2].trim();
// 解析主要计算公式
const parsedFormula = math.parse(expression);
// 提取变量
const variables = extractVariables(expression);
// 生成每个变量的不确定度项
const uncertaintyTerms = variables.map(variable => {
try {
// 计算对该变量的偏导数
const derivative = math.derivative(parsedFormula, variable);
// 生成该变量的不确定度项
return {
variable,
derivative: derivative.toString(),
term: `(${derivative.toString()} * Δ${variable})^2`
};
} catch (e) {
console.log(`跳过变量 ${variable}: ${e.message}`);
return null;
}
}).filter(term => term !== null);
// 生成不确定度传递公式
const uncertaintyFormula = `
// 不确定度传递公式推导:
1. 对各变量求偏导数:
${uncertaintyTerms.map(term =>
`∂${resultVariable}/∂${term.variable} = ${term.derivative}`
).join('\n')}
2. 不确定度传递公式:
Δ${resultVariable} = sqrt(${uncertaintyTerms.map(term => term.term).join(' + ')})
3. 相对不确定度:
Δ${resultVariable}/${resultVariable} = sqrt(${uncertaintyTerms.map(term =>
`(∂${resultVariable}/∂${term.variable} * ${term.variable}/${resultVariable} * Δ${term.variable}/${term.variable})^2`
).join(' + ')})
4. 各变量的相对不确定度:
${variables.map(v => `Δ${v}/${v}`).join(', ')}
5. 最终的相对不确定度表达式:
Δ${resultVariable}/${resultVariable} = sqrt(${variables.map(v =>
`(Δ${v}/${v})^2`
).join(' + ')})
`;
uncertaintyFormulaField.value = uncertaintyFormula;
} catch (error) {
uncertaintyFormulaField.value = `错误:无法生成不确定度公式\n${error.message}\n\n请确保:\n1. 公式格式正确\n2. 变量名合法\n3. 使用正确的数学运算符`;
}
}
// 添加到页面加载事件中
document.addEventListener('DOMContentLoaded', () => {
// ... 现有代码 ...
// 添加自动范围切换事件监听
const autoRangeCheckbox = document.getElementById('auto-range');
if (autoRangeCheckbox) {
autoRangeCheckbox.addEventListener('change', function() {
const axisRange = document.querySelector('.axis-range');
if (axisRange) {
axisRange.style.display = this.checked ? 'none' : 'block';
}
if (this.checked) {
updatePlot();
}
});
}
// 添加图表相关的事件监听器
document.querySelectorAll('#show-error-bars, #auto-range').forEach(checkbox => {
checkbox.addEventListener('change', updatePlot);
});
document.querySelectorAll('#x-min, #x-max, #y-min, #y-max').forEach(input => {
input.addEventListener('change', () => {
if (!document.getElementById('auto-range').checked) {
updatePlot();
}
});
});
});
// 在现有代码后添加导出功能
function exportData() {
const data = {
variables: [],
formula: document.getElementById('formula').value,
uncertaintyFormula: document.getElementById('uncertainty-formula').value,
results: document.getElementById('results-container').innerHTML
};
// 收集所有变量数据
document.querySelectorAll('.variable-row').forEach(row => {
data.variables.push({
name: row.querySelector('.var-name').value,
data: row.querySelector('.var-data').value,
precision: row.querySelector('.var-precision').value,
unit: row.querySelector('.var-unit').value,
uncertaintyType: row.querySelector('.uncertainty-type').value,
stats: row.dataset.stats
});
});
// 创建下载链接
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '物理实验数据_' + new Date().toISOString().slice(0,10) + '.json';
a.click();
URL.revokeObjectURL(url);
}
// 添加数据导入功能
function importData(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
try {
const data = JSON.parse(e.target.result);
// 清除现有数据
document.getElementById('variables-container').innerHTML = '';
// 导入变量数据
data.variables.forEach(v => {
const varDiv = document.createElement('div');
varDiv.className = 'variable-row';
varDiv.innerHTML = `
<input type="text" placeholder="变量名" class="var-name" value="${v.name}" oninput="validateVariableName(this)">
<textarea class="var-data" placeholder="输入多组数据,用逗号或空格分隔">${v.data}</textarea>
<input type="number" placeholder="仪器精度" class="var-precision" step="any" value="${v.precision}">
<input type="text" placeholder="单位" class="var-unit" value="${v.unit}">
<div class="uncertainty-controls">
<select class="uncertainty-type">
<option value="a" ${v.uncertaintyType === 'a' ? 'selected' : ''}>A类</option>
<option value="b" ${v.uncertaintyType === 'b' ? 'selected' : ''}>B类</option>
</select>
</div>
<div class="variable-actions">
<button onclick="removeVariable(this)">删除</button>
<button onclick="calculateVariableStats(this)">计算统计量</button>
</div>
`;
document.getElementById('variables-container').appendChild(varDiv);
if (v.stats) {
varDiv.dataset.stats = v.stats;
calculateVariableStats(varDiv.querySelector('.variable-actions button:last-child'));
}
});
// 导入公式
document.getElementById('formula').value = data.formula || '';
document.getElementById('uncertainty-formula').value = data.uncertaintyFormula || '';
// 更新变量选择下拉框
updateVariableSelects();
// 如果有结果,显示结果
if (data.results) {
document.getElementById('results-container').innerHTML = data.results;
}
} catch (error) {
alert('导入数据格式错误:' + error.message);
}
};
reader.readAsText(file);
}
// 添加单位转换功能
const UnitConverter = {
// 长度单位转换
length: {
mm: 0.001, // 毫米到米
cm: 0.01, // 厘米到米
m: 1, // 米(基准单位)
km: 1000 // 千米到米
},
// 质量单位转换
mass: {
mg: 0.000001, // 毫克到千克
g: 0.001, // 克到千克
kg: 1, // 千克(基准单位)
t: 1000 // 吨到千克
},
// 时间单位转换
time: {
ms: 0.001, // 毫秒到秒
s: 1, // 秒(基准单位)
min: 60, // 分钟到秒
h: 3600 // 小时到秒
},
// 力单位转换
force: {
N: 1, // 牛顿(基准单位)
kN: 1000, // 千牛顿到牛顿
dyn: 0.00001 // 达因到牛顿
},
// 压力单位转换
pressure: {
Pa: 1, // 帕斯卡(基准单位)
kPa: 1000, // 千帕到帕斯卡
MPa: 1000000, // 兆���到帕斯卡
atm: 101325 // 标准大气压到帕斯卡
},
// 转换函数
convert(value, fromUnit, toUnit, type) {
const units = this[type];
if (!units) throw new Error(`未支持的单位类型:${type}`);
if (!units[fromUnit]) throw new Error(`未知的源单位:${fromUnit}`);
if (!units[toUnit]) throw new Error(`未知的目标单位:${toUnit}`);
return value * units[fromUnit] / units[toUnit];
}
};
// 改进不确定度计算函数
function calculateUncertainty(data, type, params = {}) {
if (type === 'a') {
// A类不确定度计算
const n = data.length;
if (n < 2) throw new Error('A类不确定度需要至少2个数据点');
const mean = data.reduce((a, b) => a + b) / n;
const variance = data.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / (n - 1);
const standardDeviation = Math.sqrt(variance);
const uncertainty = standardDeviation / Math.sqrt(n);
return {
mean,