Thursday, 15 January 2015

PHP - Simple Math, Hard Coding. 0.000126% into fraction of 1/10000 etc -



PHP - Simple Math, Hard Coding. 0.000126% into fraction of 1/10000 etc -

this question has reply here:

how convert floats human-readable fractions? 24 answers

i need turn little percentages big fractions. if have percentage of 0.000126% - set fraction of 1/10,000 - etc. how, turn little percentage fraction not lowest mutual fraction.

the reply equation simple.

0.000126% = 0.00126/10% = 0.0126/100% = 0.126/1000% = ... = 126/1000000%

then find mutual factors. 2 goes each, that's same 63/500000. that's simple can create it.

thus, in code - how damn fraction. grrrr.... frustrating o.o! several attempts - , i'm failing @ each. ideas?

here's php function uses continued fractions find rational approximation given (positive) floating point number relative error less given tolerance.

<?php function float2frac($n, $tolerance = 1.e-6) { $h1=1; $h2=0; $k1=0; $k2=1; $b = $n; { $a = floor($b); $aux = $h1; $h1 = $a*$h1+$h2; $h2 = $aux; $aux = $k1; $k1 = $a*$k1+$k2; $k2 = $aux; $b = 1/($b-$a); } while (abs($n-$h1/$k1) > $n*$tolerance); homecoming "$h1/$k1"; } printf("%s\n", float2rat(66.66667)); # 200/3 printf("%s\n", float2rat(sqrt(2))); # 1393/985

i have written more algorithm , why works, , javascript demo here: http://jonisalonen.com/2012/converting-decimal-numbers-to-ratios/

php math

No comments:

Post a Comment