求导.html 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>导数计算器</title>
  5. <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/11.11.1/math.js"></script>
  6. <style>
  7. body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
  8. .container { background-color: #f5f5f5; padding: 20px; border-radius: 8px; }
  9. input { width: 300px; padding: 8px; margin: 10px 0; }
  10. button { background-color: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
  11. button:hover { background-color: #45a049; }
  12. #result { margin-top: 20px; font-weight: bold; }
  13. </style>
  14. </head>
  15. <body>
  16. <div class="container">
  17. <h2>导数计算器</h2>
  18. <p>输入函数表达式(使用 x 作为变量)(ln x 请写成log(x)):</p>
  19. <input type="text" id="functionInput" placeholder="例如:x^2 + 3*x + sin(x)" onkeypress="handleEnter(event)">
  20. <br>
  21. <button onclick="calculateDerivative()">计算导数</button>
  22. <div id="result"></div>
  23. </div>
  24. <script>
  25. function calculateDerivative() {
  26. const input = document.getElementById('functionInput').value;
  27. const resultDiv = document.getElementById('result');
  28. try {
  29. // 使用 math.js 计算导数
  30. const derivative = math.derivative(input, 'x');
  31. // 将结果转换为字符串并简化显示
  32. const resultString = derivative.toString()
  33. .replace(/(\^)/g, '<sup>$1</sup>')
  34. .replace(/\*/g, '');
  35. resultDiv.innerHTML = `导数结果:<span style="color: #2c3e50;">${resultString}</span>`;
  36. } catch (error) {
  37. resultDiv.innerHTML = `<span style="color: red;">错误:${error.message}</span>`;
  38. }
  39. }
  40. function handleEnter(event) {
  41. if (event.key === 'Enter') {
  42. calculateDerivative();
  43. }
  44. }
  45. </script>
  46. </body>
  47. </html>