Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 38075
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T14:39:03+00:00 2026-05-10T14:39:03+00:00

Is there any feasible way of using generics to create a Math library that

  • 0

Is there any feasible way of using generics to create a Math library that does not depend on the base type chosen to store data?

In other words, let’s assume I want to write a Fraction class. The fraction can be represented by two ints or two doubles or whatnot. The important thing is that the basic four arithmetic operations are well defined. So, I would like to be able to write Fraction<int> frac = new Fraction<int>(1,2) and/or Fraction<double> frac = new Fraction<double>(0.1, 1.0).

Unfortunately there is no interface representing the four basic operations (+,-,*,/). Has anybody found a workable, feasible way of implementing this?

  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T14:39:03+00:00Added an answer on May 10, 2026 at 2:39 pm

    Here is a way to abstract out the operators that is relatively painless.

        abstract class MathProvider<T>     {         public abstract T Divide(T a, T b);         public abstract T Multiply(T a, T b);         public abstract T Add(T a, T b);         public abstract T Negate(T a);         public virtual T Subtract(T a, T b)         {             return Add(a, Negate(b));         }     }      class DoubleMathProvider : MathProvider<double>     {         public override double Divide(double a, double b)         {             return a / b;         }          public override double Multiply(double a, double b)         {             return a * b;         }          public override double Add(double a, double b)         {             return a + b;         }          public override double Negate(double a)         {             return -a;         }     }      class IntMathProvider : MathProvider<int>     {         public override int Divide(int a, int b)         {             return a / b;         }          public override int Multiply(int a, int b)         {             return a * b;         }          public override int Add(int a, int b)         {             return a + b;         }          public override int Negate(int a)         {             return -a;         }     }      class Fraction<T>     {         static MathProvider<T> _math;         // Notice this is a type constructor.  It gets run the first time a         // variable of a specific type is declared for use.         // Having _math static reduces overhead.         static Fraction()         {             // This part of the code might be cleaner by once             // using reflection and finding all the implementors of             // MathProvider and assigning the instance by the one that             // matches T.             if (typeof(T) == typeof(double))                 _math = new DoubleMathProvider() as MathProvider<T>;             else if (typeof(T) == typeof(int))                 _math = new IntMathProvider() as MathProvider<T>;             // ... assign other options here.              if (_math == null)                 throw new InvalidOperationException(                     'Type ' + typeof(T).ToString() + ' is not supported by Fraction.');         }          // Immutable impementations are better.         public T Numerator { get; private set; }         public T Denominator { get; private set; }          public Fraction(T numerator, T denominator)         {             // We would want this to be reduced to simpilest terms.             // For that we would need GCD, abs, and remainder operations             // defined for each math provider.             Numerator = numerator;             Denominator = denominator;         }          public static Fraction<T> operator +(Fraction<T> a, Fraction<T> b)         {             return new Fraction<T>(                 _math.Add(                   _math.Multiply(a.Numerator, b.Denominator),                   _math.Multiply(b.Numerator, a.Denominator)),                 _math.Multiply(a.Denominator, b.Denominator));         }          public static Fraction<T> operator -(Fraction<T> a, Fraction<T> b)         {             return new Fraction<T>(                 _math.Subtract(                   _math.Multiply(a.Numerator, b.Denominator),                   _math.Multiply(b.Numerator, a.Denominator)),                 _math.Multiply(a.Denominator, b.Denominator));         }          public static Fraction<T> operator /(Fraction<T> a, Fraction<T> b)         {             return new Fraction<T>(                 _math.Multiply(a.Numerator, b.Denominator),                 _math.Multiply(a.Denominator, b.Numerator));         }          // ... other operators would follow.     } 

    If you fail to implement a type that you use, you will get a failure at runtime instead of at compile time (that is bad). The definition of the MathProvider<T> implementations is always going to be the same (also bad). I would suggest that you just avoid doing this in C# and use F# or some other language better suited to this level of abstraction.

    Edit: Fixed definitions of add and subtract for Fraction<T>. Another interesting and simple thing to do is implement a MathProvider that operates on an abstract syntax tree. This idea immediately points to doing things like automatic differentiation: http://conal.net/papers/beautiful-differentiation/

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there any way that I can create a new delegate type based on
Is there any way to programmatically search GMail, preferably using C#? For example, I'd
Is there any way to detect and handle whether a Java library is correctly
Is there any easy reasonable/feasible way to efficiently pipeline results from the database? I
Is there any way to change the BackColor of the border of a panel
Is there any way I can run class files (i.e. with main as the
Is there any way to view the reduction steps in haskell, i.e trace the
Is there any advantage of using int vs varbinary for storing bit masks in
Is there any way to change the icon of an application after it is
Is there any way to validate the contents of a CEdit box without subclassing?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.