C语言实现求导求积分

之前一直奇怪为什么c++只有Eigen这个库用来处理矩阵,为什么没有高等数学的库呢?今天我明白了,因为自己实现非常简单!

app.c

#include <math.h>
#include <stdio.h>

typedef double (*fun)(double x);
double Δx = 0.00000001;

double derivative(fun f, double x) {
  double Δy = f(x + Δx) - f(x);
  return Δy / Δx;
}

double integrate(fun f, double x1, double x2) {
  double y = 0;
  // 这个循环次数很多,需要使优化
  // scipy计算的速度就特别块
  for (double x = x1; x <= x2; x += Δx) {
    y += (f(x + Δx) - f(x));
  }

  return y;
}

double f1(double x) {
  // x * * 3 + 3 * *x
  return pow(x, 3) + pow(3, x);
}

int main() {
  double d = derivative(f1, 1.0);
  printf("Δy/Δx (x=1.0): %lf\n", d);  // Δy/Δx (x=1.0): 6.295837

  double i = integrate(f1, 1.0, 5.0);
  printf("i: %lf\n", i);  // i: 364.000002
  return 0;
}

makefile

app: app.c
	gcc -o $@ $^ -lm

run:
	./app

posted on 2023-07-15 18:10  Netsharp  阅读(110)  评论(0编辑  收藏  举报

导航