C语言实现求导

发布时间 2023-07-15 18:13:07作者: Netsharp

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

app.c

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

typedef double (*fun)(double x);

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

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
  return 0;
}

makefile

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

run:
	./app