For those of you that don't/won't include basic math libraries in your programs, you probably do something like this for your root functions:
double sqrt( double whole ) {double accumulator = 1.0;double difference = whole - 1.0;for( int i = 0; i < 54; ++i ) {difference /= 2.0;if( whole < SQUARE( accumulator ) == whole < SQUARE( accumulator + difference ) ) {accumulator += difference;}}return accumulator;}
Yucky. Objects are cool, so join the crowd. Here is an example program, which shows how you can just shove all the computation up front.
#define ROOTSET 2 #include <stdlib.h>double power( double base, long exponent ) { double scraper = 1.0; while( exponent != 1 ) { if( exponent % 2 == 1 ) { scraper *= base; } base *= base; exponent /= 2; } return base * scraper;}typedef struct { double spacing; long tablesize; double * table;} RootTable;RootTable roottable_init( long mode, double spacing, long tablesize ) { RootTable retval; retval . spacing = power( spacing, mode ); retval . tablesize = tablesize; retval . table = malloc( sizeof( double ) * tablesize ); long index = 0; for( long i = 0; ; ++i ) { for( long u = 0; u < power( i + 1, mode ) - power( i, mode ); ++u ) { retval . table[ index ] = spacing * ( ( double )( i ) + ( double )( u ) / ( double )( power( i + 1, mode ) - power( i, mode ) ) ); if( ++index >= tablesize ) { return retval; } } }}#define ISPOS( X ) ( X + X > X )double roottable_get( RootTable self, double searchval ) { if( ISPOS( searchval ) && ( long )( searchval / self . spacing ) < self . tablesize ) { return self . table[ ( long )( searchval / self . spacing ) ]; } else { return 0.0; }}void roottable_free( RootTable self ) { free( self . table );}#include <stdio.h>int main() { double spacing; long tablesize; scanf( "%lf %ld", & spacing, & tablesize ); RootTable subject = roottable_init( ROOTSET, spacing, tablesize ); while( 1 ) { double searchval; if( scanf( "%lf", & searchval ) == 1 ) { printf( "%lf\n", roottable_get( subject, searchval ) ); } else { roottable_free( subject ); printf( "End Program\n" ); return 0; } }}
Only braindead apes use functional programming in the big 25. Look at how smart I am, using objects in my C code.