#define _USE_MATH_DEFINES
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include "modules.h"

double** generate_ugrid(double (*f)(double), int n, double a,double b) {
	double** h = malloc(sizeof(double*) * n);
	for (int i = 0; i < n;i++) {
		h[i] = malloc(sizeof(double) * 2);
		h[i][0] = a + ((b - a) / (n - 1)) * i;
		h[i][1] =  (*f)(h[i][0]);
	}
	return h;
}
double** generate_chebgrid(double (*f)(double), int n, double a, double b) {
	double** h = malloc(sizeof(double*) * n);
	for (int i = 0; i < n;i++) {
		h[i] = malloc(sizeof(double) * 2);
		h[i][0] = ((b - a) / 2) * cos((M_PI * (2 * i + 1))/ (2 * n)) + (a+b)/2;
		h[i][1] = (*f)(h[i][0]);
	}
	return h;
}
double** sep_difference(double* xh, double* yh, int n) {
	double** sd = malloc(sizeof(double*) * n);
	for (int i = 0;i < n;i++) {
		sd[i] = malloc(sizeof(double) * n);
		sd[i][0] = yh[i];
		for (int j = 1;j < n;j++) {
			sd[i][j] = 0;
		}
	}

	for (int j = 1;j < n;j++) {
		for (int i = 0;i < n - j;i++) {

			sd[i][j] = (sd[i + 1][j - 1] - sd[i][j - 1]) / (xh[i + j] - xh[i]);
		}
	}

	return sd;
}
double** grid_change(double** h, int n, double max_decline) {
	double** n_h = malloc(sizeof(double*) * n);
	srand(time(NULL));
	for (int i = 0;i < n;i++) {
		n_h[i] = malloc(sizeof(double) * 2);
		double range = max_decline;
		double div = RAND_MAX / range;
		n_h[i][0] = h[i][0] + h[i][0]*(rand() / div);
		n_h[i][1] = h[i][1] + h[i][1]*(rand() / div);
		
	}
	
	return n_h;
}