c++ - Possible Code Speed Optimisations? -


ok have trig class use store static table of values faster execution of sin, cos, , tan functions in program. there comments and/or speed improvements made on current method? previous answers, feeling more competent c++.

trig.h

#pragma once #include <math.h>  class trig { private:     struct table     {         static const int multiple = 10; // accurately stores values 1/10 of degree         double sin[360*multiple];         table();     };     static const table table;     static void shrinkrange(double*); // shrinks degrees range 0-359 proper array indexing public:     static double sin(double);     static double cos(double);     static double tan(double); }; 

trig.cpp

#include "trig.h"  trig::table::table() // table constructor {     double const pi = 3.14159265358979323;     double const degtorad = pi/180.0;     double const incr = 1.0/multiple;     int index = 0;     (double angle = 0; index != 360*table.multiple; angle += incr)         table::sin[index++] = _inc_math::sin(angle*degtorad); }  trig::table const trig::table; // initialize static table member  void trig::shrinkrange(double* degrees) {     if (*degrees >= 360)         *degrees -= 360*( (int)*degrees/360);     if (*degrees < 0)         *degrees += 360*( -(int)*degrees/360 + 1); }  double trig::sin(double degrees) {     shrinkrange(&degrees);     degrees *= table.multiple;     return trig::table.sin[(int)(degrees+0.5)]; }  double trig::cos(double degrees) {     return trig::sin(degrees + 90); }  double trig::tan(double degrees) {     return trig::sin(degrees)/trig::cos(degrees); } 

c++ isn't java. in case, cannot call function or access member on class, because there no class objects; can access static member specifying scope:

trig::createtable(); trig::cos_table[120]; 

also (but true in java well), can automatically ensure proper initialization using dynamic initialization. if want keep current structure, add like:

bool initted = (trig::createtable(), true); 

any @ namespace scope. more idiomatic define object type contain 2 tables, constructor initialized them, , declare static instance of this:

class trig { public:     struct tables     {         double sin[360];         double cos[360];         tables();     };     static tables const tables;     //  ... };  trig::tables const trig::tables;  trig::tables::tables() {     double rad = pi / 180.0;     ( int angle = 0; angle != 360; ++ angle ) {         sin[angle] = std::sin( angle * rad );         cos[angle] = std::cos( angle * rad );     } } 

no need explicitly call trig::createtable; compiler takes care of you.

(similar techniques available in java. reason, not used, above idiomatic c++.)


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -