Inactive Tutor answered 2d
Tutor
New to Wyzant
Here is a basic algorithm using the newton raphson method to find derivates:
static inline double TotalCost(const double q) {
return 1000.0 + 30.0*q - 25.0*q*q - 4.0*q*q*q;
}
// Marginal Cost (derivative of TC)
static inline double MarginalCost(const double q) {
return 30.0 - 50.0*q - 12.0*q*q;
}
static inline double AverageCost(const double q) {
if (q <= 0.0) return NAN;
return TotalCost(q) / q;
}
// Derivative of Average Cost (to find minimum)
static inline double dAC(const double q) {
if (q <= 0.0) return NAN;
return -1000.0/(q*q) - 25.0 - 8.0*q;
}
// Second derivative of AC (for Newton's method)
static inline double d2AC(const double q) {
if (q <= 0.0) return NAN;
return 2000.0/(q*q*q) - 8.0;
}
// Newton-Raphson to find root of dAC(q)=0
// Returns root if found and positive, otherwise NAN
double findMinAC(const double initial_guess, const int max_iter, const double tol) {
double q = initial_guess;
for (int i = 0; i < max_iter; i++) {
double f = dAC(q);
if (fabs(f) < tol) return q;
double df = d2AC(q);
if (fabs(df) < 1e-12) break; // avoid division by zero
double q_new = q - f / df;
if (q_new <= 0.0) break; // only positive quantities are meaningful
q = q_new;
}
return NAN;
}
int main(void) {
double q;
printf("Enter quantity q (positive): ");
if (scanf("%lf", &q) != 1 || q <= 0.0) {
printf("Invalid input. Please enter a positive number.\n");
return EXIT_FAILURE;
}
printf("\n--- Results for q = %.4f ---\n", q);
printf("Total Cost (TC) = %.4f\n", TotalCost(q));
printf("Marginal Cost (MC) = %.4f\n", MarginalCost(q));
printf("Average Cost (AC) = %.4f\n", AverageCost(q));
printf("Derivative of AC = %.4f\n", dAC(q));
return EXIT_SUCCESS;
}