Calculator/wasm.h

62 lines
1.8 KiB
C
Raw Normal View History

2023-11-27 15:14:06 +01:00
#ifndef _WASM_H_DEF
#define _WASM_H_DEF
#include <stdio.h>
#include <math.h>
struct Canvas {
double width, height;
double xscale, yscale;
double xofset, yofset;
float xt (const double x) const {
return float (xscale * (x - xofset));
}
float yt (const double y) const {
return float (height - yscale * (y - yofset));
}
};
static const char * multipliers [] = {"f","p","n","μ","m","","k","M","G","T","P"};
struct Stepping {
double b,e,s;
char fmtbuf [16];
explicit Stepping (const double from, const double to) {
double lp;
const double z = log10 (fabs (to - from));
const double fp = modf (z, & lp);
if (fp < 0.30103) s = 1.0;
else if (fp > 0.69897) s = 5.0;
else s = 2.0;
int ip = int (lp) - 1;
if (z < 0.0) ip -= 1;
s *= ::pow (10.0, double (ip));
do {
const int k = int (fabs(to - from) / s);
b = round (from / s) * s;
e = round (to / s) * s;
if (k > 50) s *= 10.0; // prevence přeplnění osy, nevím proč, ale tohle to odstraní
else break; // patrně log10() nedává přesně to, co bych čekal
} while (true);
}
void f () {printf("stepping = %g, b = %g, e = %g\n", s, b, e);}
char * ing (const double x, int n=0) {
if (fabs(x) < 0.5 * s) {
fmtbuf[n++] = ' ';
fmtbuf[n++] = '\0';
return fmtbuf;
}
if (x < 0.0) {
fmtbuf[n++] = '-';
return ing (-x, n);
}
if (x > 0.0) {
double ip;
const double fp = modf(log10(x), & ip);
int pi = ip, ofs = 5 * 3;
if (pi < -ofs) pi = -ofs;
if (pi > 18 ) pi = 18;
const div_t dt = div(pi + ofs, 3);
n += snprintf (fmtbuf + n, 16 - n, "%g%s", ::pow (10.0, fp + double (dt.rem)), multipliers [dt.quot]);
}
return fmtbuf;
}
};
#endif // _WASM_H_DEF