Post Reply 
Setting a maximum demoninator for fractions
10-03-2023, 05:34 AM
Post: #3
RE: Setting a maximum demoninator for fractions
(10-02-2023 03:53 PM)GSL007 Wrote:  I can't figure out how to set the maximum denominator for fractions in the HP Prime G2.

HP Prime doesn't have built-in functionality for that, but you can achieve a similar effect with the following program:

Code:
// Closest Fraction
EXPORT CF(x, max_d)
BEGIN
  LOCAL curr_num, best_num, best_denom, best_diff, curr_diff, d;
  best_num := ROUND(x,0);
  best_denom := 1;
  best_diff := ABS(x - best_num);

  FOR d FROM 2 TO max_d DO
    curr_num := ROUND(x * d,0); 
    curr_diff := ABS(x - curr_num / d);

    // If the current fraction is closer to x, update the best fraction
    IF curr_diff < best_diff THEN
      best_diff := curr_diff;
      best_num := curr_num;
      best_denom := d;
    END;
  END;
  exact(best_num/best_denom);
END;

Usage:
CF(fraction, max denominator):

Example:
\(CF(PI, 64) => \cfrac{201}{64}\)
\(CF(1.45, 8) => \cfrac{10}{7}\)
\(CF(0.12345,4) => 0\)

This way, you're not limited to a denominator of 4095; you can enter much larger values (but be cautious, as it may lead to lengthy calculations).

Best regards,
Piotr
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Setting a maximum demoninator for fractions - komame - 10-03-2023 05:34 AM



User(s) browsing this thread: 1 Guest(s)