Squares

General FreeBASIC programming questions.
Locked
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

@Caseih

I watched the seagulls above me , hovering still , in a 30 mph headwind , that requires zero drag.. ( i was throwing Doritos up to them. )
I watched them fall back and then glide into the headwind without flapping , that requires a vacum or negative drag.

If you could figure out how they glide into a headwind without flapping, then it could save commercial jetliners millions a year in fuel costs.

The jet stream over the U.S. flows from Alaska to Maine at about 130 mph at 30,000 ft.
So east to west planes need to expend greater fuel to travel west into a 130 mph headwind.
If they could suck into the headwind they would use less fuel.


I don't think the airplane companies fully understand aerodynamics. its all trial and error , ( they experiment till they get a wing shape that works )
Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

Albert wrote:I don't think the airplane companies fully understand aerodynamics. its all trial and error , ( they experiment till they get a wing shape that works
Birds don't understand aerodynamics, but they get lots of experience when they are young and have to live with it.
Wings are always a pragmatic compromise. An aircraft wing must be designed to survive, whatever the situation. Failure is not an option. The airplane manufacturers understand aerodynamic lift and use super-computers to optimise the internal structural engineering and the external aerodynamic profile of their wing designs.

There are polar and sub-tropical jetstreams flowing in a meandering pattern towards the east,. They encircle the Earth in both hemispheres and are continuously changing. To save fuel when possible, planes flying East get into the sub-tropical jetstreams. Planes flying West avoid the jetstream.
For jetstream observation maps up to today, take a look at; http://virga.sfsu.edu/pub/jetstream/

http://virga.sfsu.edu/pub/jetstream/jet ... norhem.gif
The northern hemisphere jetstream is very broken up and confused at the moment. Departing Japan for Vancouver looks good, but will get better over the next couple of days.

http://virga.sfsu.edu/pub/jetstream/jet ... _sohem.gif
In the south, the polar and sub-tropical jetstreams are feeding from each other. It looks good today for aircraft flying from Capetown in S.Africa to Perth in Western Australia, then on to the East Australian coast.
caseih
Posts: 2157
Joined: Feb 26, 2007 5:32

Re: Squares

Post by caseih »

No one fully understands everything. But we have developed a number of equations over the years that seem to work, and pragmatic experimentation combined with mathematical formulas seems to give us a practical understanding of aerodynamics and fluid mechanics, at least at the scales we typically operate in. Things start to change at the extremes of scale, such as very small (insects), and very fast (supersonic and hypersonic).

Like I said before, whether you think of it as sucking or pushing, the effect is the same, and the energy required is the same. I assure you bird don't magically change the shape of their wing in order to have "negative drag." What you couldn't see when you chucked Doritos up to them was the wind gradient and a possible up draft. Gradients are funny things. There can be dead calm down where you are, and a breeze up where the bird is.

It's fun to think through problems and seek for innovative solutions to things like fuel efficiency of air craft. But we have to make sure to ground ourselves in basic principles, such as newton's laws (which still generally apply on the macro scale). There's no such thing as a free lunch. Energy has to come from somewhere, even if it's to create a vacuum.

And yes experimentation does pay off greatly. Boeing is now installing scimitar winglets on 737s which increase fuel efficiency by a remarkable 2%, which is a lot of money. They work by further reducing the formation of wingtip vortices which induce a lot of drag. Neat stuff. I imagine a combination of wind tunnel tests, super computer fluid simulation, and real-world testing led to this development.
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

@Caseih

If the aerodynamics professionals, understood aerodynamics , they would not need a wind tunnel.
Yet all the auto makers and plane makers all use wind tunnels.
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

@Richard
@Dodicat

How do you turn base 256 into base 10?
Do one of you guys have some code laying around?
Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

@Albert. It all depends on how they are represented. Are they ASCII strings ?
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

@Richard

The base 256 is raw file data...how do you convert it to base 10... not right( "000" + str( file_loc[a] ) , 3 )
Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

If your base 256 is a string of bytes (that are considered to be all one integer) then you can convert it to one long base10 BCD number by using the Unpack() function from my old BigInteger code. First copy the file into a string, it converts to base10 bytes, then it converts that to ASCII if you need that. It assumes input is two's complement.

Code: Select all

' unpack a straight binary string to a decimal ascii string
Function unpack(Byref bb As bigint) As String
    Dim As bigint b
    Dim As String d
    b = bb
    d = Chr(0)   ' initial decimal output string
    Dim As Integer i, j, product, carry, sign
    ' if negative then negate, append the sign later
    If b.s[Len(b.s)-1] And 128 Then   ' negative
        sign = -1
        b = negate(b)
    End If
    ' change from base 2 to base 10
    For j = Len(b.s)-1 To 0 Step -1 ' each byte in string is base 256
        carry = b.s[j]   ' the next byte to add after multiply
        For i = Len(d)-1 To 0 Step -1
            product = 256 * d[i] + carry
            d[i] = product Mod 10
            carry = product \ 10
        Next i
        Do While carry > 0  ' output string overflows
            d = Chr(carry Mod 10) + d   ' extend output string
            carry = carry \ 10            '  as needed
        Loop
    Next j
    ' change from Ubyte to ASCII
    For i = 0 To Len(d) - 1
        d[i] = d[i] + Asc("0")
    Next i
    If sign Then d = "-" + d Else d = "+" + d
    Return d
End Function
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

@Richard

It won't run as is , by itself , do i need to include bigint.bas or bigint.bi ? , its showing errors about bigint

Can you direct me to the include file ?
dodicat
Posts: 7983
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Squares

Post by dodicat »

Hi Albert.
I assume you are still without gmp.
So I have to use my own routines.
Press a key to refresh.
<esc> to quit.
The ascii characters are the number to base 256.

Code: Select all


'==================  BIG FUNCTION ==============================
Dim Shared ADDQmod(0 To 19) As Ubyte
Dim Shared ADDbool(0 To 19) As Ubyte
For z As Integer=0 To 19
    ADDQmod(z)=(z Mod 10+48)
    ADDbool(z)=(-(10<=z))
Next z 
Dim shared As integer _Mod(0 To 99),_Div(0 To 99)
For z As Integer=0 To 99:_Mod(z)=(z Mod 10+48):_Div(z)=z\10:Next
function Qmult(a as string,b as string) as string
      var flag=0,la = len(a),lb = len(b)
      If Len(b)>Len(a) Then flag=1:swap a,b:swap la,lb
dim as ubyte n,carry,ai
    var c =string(la+lb,"0")
    for i as integer =la-1 to 0 step -1
        carry=0:ai=a[i]-48
        for j as integer =lb-1 to 0 step -1
			 n = ai * (b[j]-48) + (c[i+j+1]-48) + carry
              carry =_Div(n):c[i+j+1]=_Mod(n)
            next j
        c[i]+=carry
    next i
 if flag then swap a,b
	return ltrim(c,"0")
end function
Function plus(_num1 As String,_num2 As String) As String
    var _flag=0,n_=0
    Dim As Ubyte addup=Any,addcarry=Any
    #macro finish()
    answer=Ltrim(answer,"0")
    If _flag=1 Then Swap _num2,_num1
    Return answer
    #endmacro
    If Len(_num2)>Len(_num1) Then 
        Swap _num2,_num1
        _flag=1
        Endif
        var diff=Len(_num1)-Len(_num2)
        var answer="0"+_num1
        addcarry=0
        For n_=Len(_num1)-1 To diff Step -1 
            addup=_num2[n_-diff]+_num1[n_]-96
            answer[n_+1]=ADDQmod(addup+addcarry)
            addcarry=ADDbool(addup+addcarry)
        Next n_ 
        If addcarry=0 Then 
            finish()
        End If
        If n_=-1 Then 
            answer[0]=addcarry+48
            finish()
            Endif
            For n_=n_ To 0 Step -1 
                addup=_num1[n_]-48
                answer[n_+1]=ADDQmod(addup+addcarry)
                addcarry=ADDbool(addup+addcarry)
                If addcarry=0 Then Exit For
            Next n_
            answer[0]=addcarry+48
            finish()
        End Function
        
        

Function _divide(n1 As String,n2 As String,decimal_places As integer=10,dpflag As String="s") As String
          Dim As String number=n1,divisor=n2
          dpflag=lcase(dpflag)
          'For MOD
          dim as integer modstop
          if dpflag="mod" then 
              if len(n1)<len(n2) then return n1
              if len(n1)=len(n2) then
                  if n1<n2 then return n1
                  end if
              modstop=len(n1)-len(n2)+1
              end if
          if dpflag<>"mod" then
     If dpflag<>"s"  Then dpflag="raw" 
     end if
        Dim runcount As integer
        '_______  LOOK UP TABLES ______________
        Dim Qmod(0 To 19) As Ubyte
        Dim bool(0 To 19) As Ubyte
        For z As Integer=0 To 19
    Qmod(z)=(z Mod 10+48)
    bool(z)=(-(10>z))
Next z
Dim answer As String   'THE ANSWER STRING  

'_______ SET THE DECIMAL WHERE IT SHOULD BE AT _______
Dim As String part1,part2
#macro set(decimal)
#macro insert(s,char,position)
If position > 0 And position <=Len(s) Then
part1=Mid$(s,1,position-1)
part2=Mid$(s,position)
s=part1+char+part2
End if
#endmacro
insert(answer,".",decpos)
  answer=thepoint+zeros+answer
If dpflag="raw" Then
    answer=Mid(answer,1,decimal_places)
    End if
#endmacro
'______________________________________________
'__________ SPLIT A STRING ABOUT A CHARACTRR __________
Dim As String var1,var2
    Dim pst As integer
      #macro split(stri,char,var1,var2)
    pst=Instr(stri,char)
    var1="":var2=""
    If pst<>0 Then
    var1=Rtrim(Mid(stri,1,pst),".")
    var2=Ltrim(Mid(stri,pst),".")
Else
    var1=stri
    End if
    #endmacro
    
       #macro Removepoint(s)
       split(s,".",var1,var2)
#endmacro
'__________ GET THE SIGN AND CLEAR THE -ve __________________
Dim sign As String
          If Left(number,1)="-" Xor Left (divisor,1)="-" Then sign="-"
            If Left(number,1)="-" Then  number=Ltrim(number,"-")
            If Left (divisor,1)="-" Then divisor=Ltrim(divisor,"-")
              
'DETERMINE THE DECIMAL POSITION BEFORE THE DIVISION
Dim As integer lennint,lenddec,lend,lenn,difflen
split(number,".",var1,var2)
lennint=Len(var1)
split(divisor,".",var1,var2)
lenddec=Len(var2)

If Instr(number,".") Then 
    Removepoint(number)
    number=var1+var2
    End if
If Instr(divisor,".") Then 
    Removepoint(divisor)
    divisor=var1+var2
    End if
Dim As integer numzeros
numzeros=Len(number)
number=Ltrim(number,"0"):divisor=Ltrim (divisor,"0")
numzeros=numzeros-Len(number)
lend=Len(divisor):lenn=Len(number)
If lend>lenn Then difflen=lend-lenn
Dim decpos As integer=lenddec+lennint-lend+2-numzeros 'THE POSITION INDICATOR
Dim _sgn As Byte=-Sgn(decpos)
If _sgn=0 Then _sgn=1
Dim As String thepoint=String(_sgn,".") 'DECIMAL AT START (IF)
Dim As String zeros=String(-decpos+1,"0")'ZEROS AT START (IF) e.g. .0009
if dpflag<>"mod" then
If Len(zeros) =0 Then dpflag="s"
end if
Dim As integer runlength
If Len(zeros) Then 
     runlength=decimal_places
     answer=String(Len(zeros)+runlength+10,"0")
    If dpflag="raw" Then 
        runlength=1
        answer=String(Len(zeros)+runlength+10,"0")
        If decimal_places>Len(zeros) Then
            runlength=runlength+(decimal_places-Len(zeros))
            answer=String(Len(zeros)+runlength+10,"0")
            End If
            End If

Else
decimal_places=decimal_places+decpos
runlength=decimal_places
answer=String(Len(zeros)+runlength+10,"0")
End if
'___________DECIMAL POSITION DETERMINED  _____________

'SET UP THE VARIABLES AND START UP CONDITIONS
number=number+String(difflen+decimal_places,"0")
        Dim count As integer
        Dim temp As String
        Dim copytemp As String
        Dim topstring As String
        Dim copytopstring As String
        Dim As integer lenf,lens
        Dim As Ubyte takeaway,subtractcarry
        Dim As integer n3,diff
       If Ltrim(divisor,"0")="" Then Return "Error :division by zero"   
        lens=Len(divisor)
         topstring=Left(number,lend)
         copytopstring=topstring
        Do
            count=0
        Do
            count=count+1
            copytemp=temp
    
            Do
'___________________ QUICK SUBTRACTION loop _________________              
            
lenf=Len(topstring)
If  lens<lenf=0 Then 'not
If Lens>lenf Then
temp= "done"
Exit Do
End if
If divisor>topstring Then 
temp= "done"
Exit Do
End if
End if

  diff=lenf-lens
        temp=topstring
        subtractcarry=0
        
        For n3=lenf-1 To diff Step -1
            takeaway= topstring[n3]-divisor[n3-diff]+10-subtractcarry
            temp[n3]=Qmod(takeaway)
            subtractcarry=bool(takeaway)
        Next n3 
        If subtractcarry=0 Then Exit Do
         If n3=-1 Then Exit Do
        For n3=n3 To 0 Step -1 
            takeaway= topstring[n3]-38-subtractcarry
             temp[n3]=Qmod(takeaway)
            subtractcarry=bool(takeaway)
            if subtractcarry=0 then exit do
            Next n3
        Exit Do
        
        Loop 'single run
        temp=Ltrim(temp,"0")
        If temp="" Then temp= "0"
            topstring=temp
        Loop Until temp="done"
     ' INDIVIDUAL CHARACTERS CARVED OFF ________________       
        runcount=runcount+1
       If count=1 Then
           topstring=copytopstring+Mid(number,lend+runcount,1)
           Else
       topstring=copytemp+Mid(number,lend+runcount,1)
   End If
       copytopstring=topstring
       topstring=Ltrim(topstring,"0")
       if dpflag="mod" then
       if runcount=modstop then 
           if topstring="" then return "0"
           return mid(topstring,1,len(topstring)-1)
           end if
       end if
       answer[runcount-1]=count+47
       If topstring="" And runcount>Len(n1)+1 Then
           Exit Do
           End if
   Loop Until runcount=runlength+1
   
   ' END OF RUN TO REQUIRED DECIMAL PLACES
   set(decimal) 'PUT IN THE DECIMAL POINT
  'THERE IS ALWAYS A DECIMAL POINT SOMEWHERE IN THE ANSWER
  'NOW GET RID OF IT IF IT IS REDUNDANT
       answer=Rtrim(answer,"0")
       answer=Rtrim(answer,".")
       answer=Ltrim(answer,"0")
       If answer="" Then Return "0"
   Return sign+answer
End Function
'=======================================================================

#define mod_(a,b) _divide((a),(b),,"mod")
#define div_(a,b) iif(len((a))<len((b)),"0",_divide((a),(b),-2))



'decimal to base 256
Function convertto256(ByVal i As String) As String
	Dim As String b="256",d,m,g
	Do
    d=div_(i,b)
    m=mod_(i,b)
    g=chr(valint(m))+g
    i=d
	loop until i="0"  
	Return g
End Function


        ' ============== base 256 TO DECIMAL =================================     
        Function ConvertToBase10(Number As String) As String
            Dim As String sum
            sum=Str(Asc(Left(Number,1)))
            For n As Integer=2 To Len(Number)
                sum=plus(Qmult(sum,"256"),Str((Number[n-1])) ) 
            Next n
            Return sum
        End Function
        
        
Randomize
#define range(f,l) int(Rnd*(((l)+1)-(f))+(f))
#macro create(L)
i=string(L," ")
Do
    for n as long =0 to L-1
        i[n]=range(48,57)
    next
loop until i[0]<>48

#EndMacro
Do
	Cls

dim as string i
create(1000)
print i

  print
  print "Ascii characters"

  Dim As String b256
  b256= convertto256(i)
  Print b256
  Print
  Print
  Print "return"
  Print ConvertToBase10(b256)
  Sleep
  Loop Until InKey=Chr(27)
  
    

    
  
Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

Albert wrote: It won't run as is , by itself , do i need to include bigint.bas or bigint.bi ? , its showing errors about bigint

Can you direct me to the include file ?
BigInt is a simple string so just replace the type bigint with type string.
Delete all references to .s
The BigInt type made overloading operators possible.
The bigint code is on the FB forum.

Code: Select all

' unpack a straight binary string to a decimal ascii string
Function unpack(Byref bb As String) As String
    Dim As String b
    Dim As String d
    b = bb
    d = Chr(0)   ' initial decimal output string
    Dim As Integer i, j, product, carry, sign
    ' change from base 2 to base 10
    For j = Len(b)-1 To 0 Step -1 ' each byte in string is base 256
        carry = b[j]   ' the next byte to add after multiply
        For i = Len(d)-1 To 0 Step -1
            product = 256 * d[i] + carry
            d[i] = product Mod 10
            carry = product \ 10
        Next i
        Do While carry > 0  ' output string overflows
            d = Chr(carry Mod 10) + d   ' extend output string
            carry = carry \ 10            '  as needed
        Loop
    Next j
    ' change from Ubyte to ASCII
    For i = 0 To Len(d) - 1
        d[i] = d[i] + Asc("0")
    Next i
    Return d
End Function

dim as string txt = chr( 0, 1, 0, 0, 0 )
print unpack( txt )

sleep
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

@Richard

It requires a binary string input...

dim as string txt = chr( 1,0,0,0,0 ) , comes out to 1
dim as string txt = chr( 0,1,0,0,0 ) , comes out to 256
dim as string txt = chr( 0,0,1,0,0 ) , comes out to 65536

How do you turn the file into binary?
Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

Albert wrote:How do you turn the file into binary?
The file is a long line of bytes. Read the file into a string. Unpack will give you the file as a long base10 number.
If the file only contains the data bytes “Albert.” you will get 13075883604732993.

Code: Select all

Dim As String txt = "Albert."
Print unpack( txt )
txt = Chr( 255, 255, 0, 0, 0 )
Print unpack( txt )
txt = Chr( 0, 0, 1, 0, 0 )
Print unpack( txt )
' gives output 
13075883604732993
65535
65536
albert
Posts: 6000
Joined: Sep 28, 2006 2:41
Location: California, USA

Re: Squares

Post by albert »

@Richard

How do you turn the output back into base 256?
Richard
Posts: 3096
Joined: Jan 15, 2007 20:44
Location: Australia

Re: Squares

Post by Richard »

@Albert. You use the pack( ) function.

Code: Select all

'================================================================
' pack ascii numeric string to a straight binary number in a bigint
'================================================================
' the output bigint will have a length that is a multiple of 4 bytes
Function pack( Byref ascii As String) As String
    Dim As String a  ' a is the ascii input
    Dim As String b  ' b is the binary output
    Dim As Integer p, i, j, ch, blocks
    a = ascii
    '------------------------------------------------------------
    ' extract numerics from input string
    j = 0   '  in-place write pointer
    For i = 0 To Len(a) - 1
        ch = a[i]
        If (ch >= Asc("0")) And (ch <= Asc("9")) Then
            a[j] = ch
            j += 1
        Else
            Print "Invalid digit = "; Chr( ch ); ", in string at position ="; i
        End If
    Next i
    a = Left(a, j)  ' j is one ahead from string index = length of a
    '------------------------------------------------------------
    ' extend to next multiple of 9 digits
    i = Len(a)
    blocks = Int(0.99 + i / 9)  ' number of 9 digit blocks needed
    p = 9 * blocks
    a = String(p - i, "0") + a  ' pad to next multiple of 9 digits
    '------------------------------------------------------------
    ' decimal to binary conversion
    i = ( 8 + Len(a) * 3.32192809488) \ 8   ' bytes needed for binary
    blocks = 1 + (i \ 4)                    ' adjust to multiple of 4
    b = String(blocks * 4, Chr(0) ) ' binary destination string
    '------------------------------------------------------------
    Dim As Uinteger Ptr bp, bpz, bpcarry, bpdata
    bpz = Cast(Uinteger Ptr, Strptr(b)) ' binary output string[0]
    Dim As Ulongint product, carry, multiplier = 1e9
    bpdata = Cast(Uinteger Ptr, @product) ' bottom half of product
    bpcarry = bpdata + 1                ' top half of product
    '------------------------------------------------------------
    blocks = 1  ' blocks will be advanced as required by carry
    For i = 1 To Len(a)-8 Step 9   ' msd to lsd in blocks of 9
        bp = bpz    ' point back to the start
        carry = Valulng(Mid(a, i, 9))  ' take the next 9 digit block
        For j = 1 To blocks
            product = Clngint(*bp) * multiplier + carry
            *bp = Cuint(*bpdata)
            carry = Culngint(*bpcarry)
            bp += 1
        Next j
        ' advancing blocks only as needed doubles the speed of conversion
        If Carry Then
            *bp = carry
            blocks += 1 ' an exact count of the blocks used
        End If
    Next i
    b = Left(b, blocks * 4) ' keep only used blocks
    '-------------------------------------------------------------
    Return b
End Function

'-----------------------------------------------------------------------
' convert compressed binary string to ascii string
'-----------------------------------------------------------------------
' unpack a binary string to a decimal ascii string
Function unpack( Byref b As String ) As String
    Dim As String d = Chr( 0 )   ' initial decimal output string
    Dim As Integer i, j, product, carry
    '---------------------------------------------------
    ' change from base 256 to base 10
    For j = Len( b ) - 1 To 0 Step -1 ' bytes in base256 string, msb first
        carry = b[ j ]   ' byte to accumulate after multiply
        For i = Len( d ) - 1 To 0 Step -1   ' byte + ( decimal * 256 )
            product = 256 * d[ i ] + carry
            d[ i ] = product Mod 10
            carry = product \ 10
        Next i
        Do While carry > 0  ' output string typically overflows twice
            d = Chr( carry Mod 10 ) + d   ' extend output string
            carry = carry \ 10            '  as needed
        Loop
    Next j
    '---------------------------------------------------
    ' change from Ubyte to ASCII
    For i = 0 To Len( d ) - 1
        d[ i ] = d[ i ] + Asc( "0" )
    Next i
    Return d
End Function

'-----------------------------------------------------------------------
Dim As String txt = "Albert. "   ' little endian
Print txt; "<"
txt = unpack( txt )
Print txt; "<"
txt = pack( txt )
Print txt; "<"

'-----------------------------------------------------------------------
Sleep
'-----------------------------------------------------------------------
Locked