Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

giovanninicco http://giovanninicco.com

Physics quantities

// Physics quantities
// needs:<script src=gnmath.txt></script>
// needs: <script src=gnrandom.txt></script>
// ******************************************************************************
// ******************************************************************************
// ******************************************************************************
// ******************************************************************************
// Unit of Misur CLASS (UM) ***************************************
// an element is a string like m^2 k^3 s^(-1)
// its rappresentatios is:  [["m",2],["k",3],["s",-1]]
// (using gnmath constants definition we can also use: [[_m,2],[_k,3],[_s,-1]]
function UM(zxc){ 
	this.vv=zxc;
}
new UM([['dummy',0]]);


UM.prototype.toString=function(){
	this.collect();
	s=""
	for (var i=0;i<this.vv.length;i++){
		s+=' '
		s+=this.vv[i][0];
		s+=(this.vv[i][1]!=1)? '<sup>'+this.vv[i][1]+'</sup> ': ' '
	}
	return s;
}


	// +++++++++++ make the nth power of um
UM.pow=function(umis,n){// umis : is a UM!!
//	wwl('inUM.pow azsx='+azsx)
	for (var i=0;i<umis.vv.length;i++){
		umis.vv[i][1]*=n; // the name rest the same,the exponent is multiplied
	}
//	wwl('inUM.pow prima di uscire azsx='+azsx)

	return umis;
}




	// +++++++++++ collect same units
UM.prototype.collect=function(){
//	alert('collecting:'+this.vv)
	for (var i=0;i<this.vv.length;i++){
		for (var j=i+1;j<this.vv.length;j++){
			if(this.vv[i][0]==this.vv[j][0]){
				this.vv[i][1]+=this.vv[j][1]; // sum exponents
				this.vv[j][0]="";this.vv[j][1]=""} // nill last term equal
			}
		}
//	alert('collected:'+this.vv)

	for (var i=0;i<this.vv.length;i++){// nill null exponent term
			if(this.vv[i][1]==0){this.vv[i][0]="";this.vv[i][1]=""}
	}
//	ww('collected e nilled:'+this.vv)



	this.vv.sort(); // sort um alphabetically
//	ww('collected e sorted:'+this.vv)

	return this.vv;
}




	// +++++++++++++ multiply(x,y)  returns a string with um multiplied 
UM.multiply=function(x,y){
	var k=0;
	newVett=new Array() // a new array will collect all terms from two strings



	for(var i=0;i<x.vv.length;i++){// loading first element terms
		var a1=new Array();
			a1[0]=x.vv[i][0]  // um name
			a1[1]=x.vv[i][1]  // um exponent
		newVett[i]=a1;
	}
	for(var j=0;j<y.vv.length;j++){// // loading second element terms
		var a2=new Array();
			a2[0]=y.vv[j][0]     // um name
			a2[1]=y.vv[j][1]     // um exponent
		newVett[i+j]=a2;
	}


//	ww('creo prodotto')
//	ww(newVett)
	var prodotto = new UM(newVett);// build & return a new um with data collected
//	ww('pp:',prodotto)
	prodotto.collect();
//	ww('pp2:',prodotto)
	return prodotto;
}





	// ++++++++++++++++ x.divide(y) returns a string with um divided
UM.divide=function(x,y){
//	alert('x='+x)
//	alert('y='+y)
	var k=0;
	newVett=new Array() //vettore che conterr� vettori da due
	for(var i=0;i<x.vv.length;i++){// carico tutti quelli di x
		var a1=new Array();
		a1[0]=x.vv[i][0]
		a1[1]=x.vv[i][1]
		newVett[i]=a1;
	}
//	alert(newVett)




	for(var j=0;j<y.vv.length;j++){// carico tutti quelli di y
		var a2=new Array();
		a2[0]=y.vv[j][0]
		a2[1]=-y.vv[j][1] // being at den power have to be inverted
		newVett[i+j]=a2;
	}
//	alert(newVett)



	var rapporto=new UM(newVett);
//	ww('rapp1='+rapporto)
	rapporto.collect();
//	ww('rapp2='+rapporto)

	return rapporto;
}





// ******************************************************************************
// ******************************************************************************
// ******************************************************************************


// ******************************************************************************
// ******************************************************************************
// ******************************************************************************
// Physical Quantity CLASS  (PQ)
// an element is a vector including a number and a um string  like (8*10^4) m^2 k^3 s^(-1)
// its rappresentatios is:  [8,4,um] ie [ 8, 4 ,  [[_m,2],[_k,3],[_s,-1]] ]



function PQ(_x,_exp,_mis){ //argomenti: x= numero; exp= potenza dieci; _mis um
	this.x=_x;
	this.exp=_exp;
	// POLIMORPHISM: if _mis is a vector:
	if(_mis.length >0 ){
		this.mis=new UM(_mis);
	}
	else{ // if _mis is already a um:
		this.mis=_mis
	}
}

new PQ(0,0,[['dummy',0]])
PQ.precision=3;
PQ.prototype.toString=function (){
	this.mis.collect();
	return (
		trunc(this.x,PQ.precision)+
		( (this.exp==0)? '':'<big><sup>'+dot+'</big></sup>'+'10<sup> '+this.exp+'</sup> '  ) +
		this.mis.toString()+' '
	)
}
PQ.prototype.clone=function(){
	var s="";
	s+=this.x;
	s+=','+this.exp
	var ss="[ "
	var comma=','
	for (var i=0;i<this.mis.vv.length;i++){
		if(i==this.mis.vv.length-1){comma=''}
		ss+= "['" + this.mis.vv[i][0] + "'," + this.mis.vv[i][1] + "]"+comma
	}

	ss+=' ]'
	s+=','+ss
	return s;
}


PQ.multiply=function(x,y){
	return new PQ( x.x*y.x, x.exp+y.exp ,UM.multiply(x.mis,y.mis) );
}



PQ.pow=function(x,n){
//	wwl('inPQ.pow azsx='+azsx)
	return (new PQ( Math.pow(x.x,n), x.exp * n ,UM.pow(x.mis,n))  );
}

PQ.divide=function(x,y){
	return new PQ( x.x/y.x, x.exp-y.exp ,UM.divide(x.mis,y.mis));
}



PQ.sum=function(x,y){
	var z=x.x*Math.pow(10,x.exp)+y.x*Math.pow(10,y.exp)
	return new PQ( z, 0 ,x.mis);
}

PQ.diff=function(x,y){
	var z=x.x*Math.pow(10,x.exp)-y.x*Math.pow(10,y.exp)
	return new PQ( z, 0 ,x.mis);
}



PQ.scalarMultiply=function(x,n){
	var z=(x.x*Math.pow(10,x.exp) ) *n
	return new PQ( z, 0 ,x.mis);
}

PQ.prototype.normalize=function(){
	// Adjust mantissa to x.yyy
	var og=Math.round(log10(this.x));
	this.x/=Math.pow(10,og);
	this.exp=(this.exp*1+og*1)
	return this;
}
//***********************


graph library

// graph library
//   A library to implement graphic on JavaScript by Giovanni Nicco
//   Commands have  Java syntax
//
//
//                                
//   drawArc(x,y,l,h,alpha0,alpha1): draw an arc of oval from alpha0 to alpha1 (radians)
//   drawImage(x,y,fileName) : draws an image (fileName) in x,y 
//   drawOval(x,y,width,heigth): draw an oval (or circle) (use last setColor color)
//   drawLine(x0,y0,x1,y1): draws a line from x0,y0 to x1,y1
//   drawRect(x0,y0,width,heigth): draws a rectangle
//   drawString(s,x,y): draws a strings s in x,y
//   fillArc(x,y,l,h,alpha0,alpha1): draw a filled arc of oval from alpha0 to alpha1 (radians)
//   fillRect(x0,y0,width,heigth,color): draw a filled rectangle (need color)
//   fillOval(x,y,width,heigth): draw a filled oval (or circle) (use last setColor color)
//   setColor(c); sets the color of next figures to be c (unsetted color is black)
//   setPoint(x,y); draw a point in x,y (black or of the color setted by setColor()
var red='red';
var green='green';
var blue='blue';

function drawArc(x,y,l,h,alpha0,alpha1){
		rx=l/2;ry=h/2;
		xc=x+rx;yc=y+ry
		da=Math.PI/360
		for(var alpha=alpha0;alpha<=alpha1;alpha+=da){
			drawLine(xc+rx*Math.cos(alpha),yc-ry*Math.sin(alpha),xc+rx*Math.cos(alpha+da),yc-ry*Math.sin(alpha+da));
		}
}

function drawImage(x,y,i) {
    document.writeln('<SPAN STYLE="position:absolute; left:'+x+'px; top:'+y+'px"><img src="'+i+'"></SPAN>');
}

function drawLine(x0,y0,x1,y1){
	dx=x1-x0;dy=y1-y0;
	if(y1>=y0){versoy=1}else{versoy=-1}
	if(x1>=x0){versox=1}else{versox=-1}
	npx=Math.abs(dx);npy=Math.abs(dy);
	var i=0;
	if( dx*dx >= dy*dy){ // tg <= 45�
		deY=dy/npx;
		with(document){
			while(i++<=npx){
				write('<SPAN STYLE="position:absolute; left:' +x0+ '; top:' +y0+ '">.</SPAN>');
				x0+=versox;y0+=deY
			}
		}
	}
	else{ // tg > 45�
		deX=dx/npy;
		with(document){
			while(i++<=npy){
				write('<SPAN STYLE="position:absolute; left:' +x0+ '; top:' +y0+ '">.</SPAN>');
				y0+=versoy;x0+=deX;
		        }
	        }
         }
}

function drawOval(x,y,l,h){
	rx=l/2;ry=h/2;
	xc=x+rx;yc=y+ry
	da=Math.PI/360
	for(var alpha=0;alpha<=6.29;alpha+=da){
		drawLine(xc+rx*Math.cos(alpha),yc- ry*Math.sin(alpha),xc+rx*Math.cos(alpha+da),yc- ry*Math.sin(alpha+da));
	}
}


function drawRect(x0,y0,l,h){
	x0=Math.floor(x0);y0=Math.floor(y0);
	l=Math.ceil(l);h=Math.ceil(h);
	drawLine(x0,y0,x0+l,y0);
	drawLine(x0,y0,x0,y0+h);
	drawLine(x0+l,y0+h,x0+l,y0);
	drawLine(x0+l,y0+h,x0,y0+h);
}

function drawString(s,x,y){
	document.write('<SPAN STYLE="position:absolute; left:' +x+ 'px; top:' +y+ 'px">'+s+'</SPAN>');
}


function fillArc(x,y,l,h,alpha0,alpha1){
	rx=l/2;ry=h/2;
	xc=x+rx;yc=y+ry
	da=Math.PI/180
	for(var alpha=alpha0;alpha<=alpha1;alpha+=da){
		drawLine(xc,yc,xc+rx*Math.cos(alpha+da),yc-ry*Math.sin(alpha+da));
	}
}


function fillOval(x,y,l,h){
	var rx=l/2; var ry=h/2;
	var xc=x+rx;var yc=y+ry
	for(var xx=x+l;xx>=-x;xx--){
		alpha=Math.acos((xx-x)/l)
		drawLine(xc+rx*Math.cos(alpha),yc-ry*Math.sin(alpha),xc+rx*Math.cos(-alpha),yc-ry*Math.sin(-alpha));
	}
}

function fillRect(x,y,w,h,color){
	document.write(	'<DIV STYLE="position: absolute; top:'+	y+'; left:'+
	x+'; width:'+w+	'; height:'+h+'; background-color: '+	color+' "   ></div>'	)
}





function setColor(c){
	document.write('<font color='+c+'>');
}



function setPoint(x,y){ 
	document.write('  <SPAN STYLE="position:absolute; left:' +x+ 'px; top:' +y+ 'px">.</SPAN> ' );
}






Peter Jipsen library for math rendering

// math rendering

/*
ASCIIMathML.js
==============
This file contains JavaScript functions to convert ASCII math notation
to Presentation MathML. The conversion is done while the (X)HTML page 
loads, and should work with Firefox/Mozilla/Netscape 7+ and Internet 
Explorer 6+MathPlayer (http://www.dessci.com/en/products/mathplayer/).
Just add the next line to your (X)HTML page with this file in the same folder:
<script type="text/javascript" src="ASCIIMathML.js"></script>
This is a convenient and inexpensive solution for authoring MathML.

Version 1.4.7 Aug 7, 2005, (c) Peter Jipsen http://www.chapman.edu/~jipsen
Latest version at http://www.chapman.edu/~jipsen/mathml/ASCIIMathML.js
For changes see http://www.chapman.edu/~jipsen/mathml/asciimathchanges.txt
If you use it on a webpage, please send the URL to jipsen@chapman.edu

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License (at http://www.gnu.org/copyleft/gpl.html) 
for more details.
*/

var checkForMathML = true;   // check if browser can display MathML
var notifyIfNoMathML = true; // put note at top of page if no MathML capability
var mathcolor = "blue";       // change it to "" (to inherit) or any other color
var mathfontfamily = "serif"; // change to "" to inherit (works in IE) 
                              // or another family (e.g. "arial")
var displaystyle = true;      // puts limits above and below large operators
var showasciiformulaonhover = true; // helps students learn ASCIIMath
var decimalsign = ".";        // change to "," if you like, beware of `(1,2)`!
var AMdelimiter1 = "`", AMescape1 = "\\\\`"; // can use other characters
var AMdelimiter2 = "$", AMescape2 = "\\\\\\$", AMdelimiter2regexp = "\\$";
var doubleblankmathdelimiter = false; // if true,  x+1  is equal to `x+1`
                                      // for IE this works only in <!--   -->
//var separatetokens;// has been removed (email me if this is a problem)
var isIE = document.createElementNS==null;

if (document.getElementById==null) 
  alert("This webpage requires a recent browser such as\
\nMozilla/Netscape 7+ or Internet Explorer 6+MathPlayer")

// all further global variables start with "AM"

function AMcreateElementXHTML(t) {
  if (isIE) return document.createElement(t);
  else return document.createElementNS("http://www.w3.org/1999/xhtml",t);
}

function AMnoMathMLNote() {
  var nd = AMcreateElementXHTML("h3");
  nd.setAttribute("align","center")
  nd.appendChild(AMcreateElementXHTML("p"));
  nd.appendChild(document.createTextNode("To view the "));
  var an = AMcreateElementXHTML("a");
  an.appendChild(document.createTextNode("ASCIIMathML"));
  an.setAttribute("href","http://www.chapman.edu/~jipsen/asciimath.html");
  nd.appendChild(an);
  nd.appendChild(document.createTextNode(" notation use Internet Explorer 6+"));  
  an = AMcreateElementXHTML("a");
  an.appendChild(document.createTextNode("MathPlayer"));
  an.setAttribute("href","http://www.dessci.com/en/products/mathplayer/download.htm");
  nd.appendChild(an);
  nd.appendChild(document.createTextNode(" or Netscape/Mozilla/Firefox"));
  nd.appendChild(AMcreateElementXHTML("p"));
  return nd;
}

function AMisMathMLavailable() {
  if (navigator.appName.slice(0,8)=="Netscape") 
    if (navigator.appVersion.slice(0,1)>="5") return null;
    else return AMnoMathMLNote();
  else if (navigator.appName.slice(0,9)=="Microsoft")
    try {
        var ActiveX = new ActiveXObject("MathPlayer.Factory.1");
        return null;
    } catch (e) {
        return AMnoMathMLNote();
    }
  else return AMnoMathMLNote();
}

// character lists for Mozilla/Netscape fonts
var AMcal = [0xEF35,0x212C,0xEF36,0xEF37,0x2130,0x2131,0xEF38,0x210B,0x2110,0xEF39,0xEF3A,0x2112,0x2133,0xEF3B,0xEF3C,0xEF3D,0xEF3E,0x211B,0xEF3F,0xEF40,0xEF41,0xEF42,0xEF43,0xEF44,0xEF45,0xEF46];
var AMfrk = [0xEF5D,0xEF5E,0x212D,0xEF5F,0xEF60,0xEF61,0xEF62,0x210C,0x2111,0xEF63,0xEF64,0xEF65,0xEF66,0xEF67,0xEF68,0xEF69,0xEF6A,0x211C,0xEF6B,0xEF6C,0xEF6D,0xEF6E,0xEF6F,0xEF70,0xEF71,0x2128];
var AMbbb = [0xEF8C,0xEF8D,0x2102,0xEF8E,0xEF8F,0xEF90,0xEF91,0x210D,0xEF92,0xEF93,0xEF94,0xEF95,0xEF96,0x2115,0xEF97,0x2119,0x211A,0x211D,0xEF98,0xEF99,0xEF9A,0xEF9B,0xEF9C,0xEF9D,0xEF9E,0x2124];

var CONST = 0, UNARY = 1, BINARY = 2, INFIX = 3, LEFTBRACKET = 4, 
    RIGHTBRACKET = 5, SPACE = 6, UNDEROVER = 7, DEFINITION = 8,
    LEFTRIGHT = 9, TEXT = 10; // token types

var AMsqrt = {input:"sqrt", tag:"msqrt", output:"sqrt", tex:null, ttype:UNARY},
  AMroot  = {input:"root", tag:"mroot", output:"root", tex:null, ttype:BINARY},
  AMfrac  = {input:"frac", tag:"mfrac", output:"/",    tex:null, ttype:BINARY},
  AMdiv   = {input:"/",    tag:"mfrac", output:"/",    tex:null, ttype:INFIX},
  AMover  = {input:"stackrel", tag:"mover", output:"stackrel", tex:null, ttype:BINARY},
  AMsub   = {input:"_",    tag:"msub",  output:"_",    tex:null, ttype:INFIX},
  AMsup   = {input:"^",    tag:"msup",  output:"^",    tex:null, ttype:INFIX},
  AMtext  = {input:"text", tag:"mtext", output:"text", tex:null, ttype:TEXT},
  AMmbox  = {input:"mbox", tag:"mtext", output:"mbox", tex:null, ttype:TEXT},